Hi again!

I'm having problems with an assignment once again. It's asking us to write a program that takes in a phone number as a string in the form of (555)555-555. We're then to use the strtok_s function to split the phone number into the area code, prefix, and then the number. Once we've done that, we're supposed to concatenate the 7 digits into one string and print out both area code and phone number.

That being explained, I have used the strtok_s function to split the number up into area code, prefix and number. I'm not sure how to concatenate them into one string. Any suggestions? Here's my code. The cout statements inside the if statements are just to make sure I've done the tokens right.

#include <iostream>
#include <cstring>
using namespace std;

int main()

	char phone_number[14];
	char pnumber[14];
	char *areaCode;
	char *prefix;
	char *number;
	char *next_token;
	char tok_val[] = {"-" "(" ")"};
	int counter = 0;

	cout<< "Please enter a phone number (using parentheses and hyphens): " <<endl;
	cin.getline(phone_number, 14, '\n');

		for(int i = 0; i < 14; i++)
			pnumber[i]= ' ';
		areaCode = strtok_s(phone_number, tok_val, &next_token);
			if(areaCode != NULL)
			prefix = strtok_s(NULL, tok_val, &next_token);

				if(prefix != NULL)
				number = strtok_s(NULL, tok_val, &next_token);
				if (number != NULL)

return 0;

Thanks for your time!


7 Years
Discussion Span
Last Post by Ancient Dragon

This is c++, not C, so just use the std::string + operator to concantinate strings

std::string areaCode = "999";
std::string prefix = "555";
std::string number = "1212";

std::string result = areaCode + " " + prefix + "-" + number;

If you have to use character arrays then use strcat() to concantinate the strings

char areaCode[] = "999";
char prefix[] = "555";
char number[] = "1212";
char result[126] = {0};
strcat(result, areaCode);
strcat(result," ");
strcat(result, previx);
strcat(result, number);
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.