I am prompting the user for a phone number in my program. The problem is is you never know how the user will input the number. Is there a way to check the input and automatically format the phone number as (###) ###-####. Thanks for the help.
I suppose that since a phone number is meaningful if seen as a sequence of digits and not as a whole number, you could create an array of 10 chars to hold the digits.
char number[10];
Then you can use a while loop where in each iteration you read one character. If this character is a digit you place it in the array, in the proper slot (it would be very useful if you had an integer variable to hold the number of numeric inputs so far entered by the user)
1 2 3 4 5 6 7
int num_count=0;
char ch;
while (num_count<10)
{
cin.get(ch);
if (/*here you check if ch is a digit*/) number[num_count++]=ch;
}
I'll let you discover on your own how to check if the current character is a digit. There's a c-library function that does the job, but you can always do it manually ;) Oh, and after you get the number it would be useful to flush your input buffer:
while (cin.get()!='\n');
Now that you have the information you want, you can output it in any format you like, just play with cout for a while and you'll get it right eventually.