-
strtok() a phone number
What i gotta do:
Write a program that inputs a tele phone #as astring in the form (555)555-5555. The program should use function strok() to extract the area code as a token , the first three digits of the phone # as a token and the last four as a token. the seven digits of the phone should be concatenated into one string.The program should convert the are-code string to int and convert the phone # string to long. both the area-code and the phone #should be printed
Output:
Code:
Enter a phone number in the form (555) 555-5555:
(555)555-5555
The integer area code is 555
The long integer phone number is 555555
press any key to continue...
What i got sofar:
Code:
#include <stdio.h>
#include <string.h>
int main()
{
char string[ 10 ];
char *tokenPtr;
printf( "Enter a phone number in the form (555) 555-5555: \n" );
scanf( "%s", string);
tokenPtr = strtok( string, "() -" );
while ( tokenPtr != NULL ){
printf( "\nThe integer area code is %s\n", tokenPtr );
tokenPtr = strtok( NULL, "() -" );
}
return 0;
}
its only a bit of it i dont know how to set it up with gets, stoi(), strcopy(), and strcat()
-
>scanf( "%s", string);
Let's do the math, k? string is 10 characters long, but you require the format of (assuming no internal whitespace) (xxx)xxx-xxxx, which is 13 characters. Add the null character at the end and it's 14, at the very least. Since you don't use a field width modifier for %s, scanf will happily read until whitespace is encountered, so (once again assuming no internal whitespace), you're looking at a guaranteed buffer overflow. How would you describe that call to scanf as anything but an assured failure?
>while ( tokenPtr != NULL ){
There's really no need for a loop. Since this clearly isn't meant to be a rock solid program, you can just assume that the number is formatted properly and go about your business:
Code:
#include <stdio.h>
#include <string.h>
int main ( void )
{
char buffer[BUFSIZ];
char area[4] = {0};
char number[9] = {0};
char *p;
printf ( "Enter a phone number (ex. (555) 555-5555): " );
gets ( buffer ); /* I weep as I type this */
p = strtok ( buffer, "()- " );
if ( p != NULL )
strncat ( area, p, sizeof area - 1 );
p = strtok ( NULL, "()- " );
if ( p != NULL )
strncat ( number, p, sizeof number - 1 );
p = strtok ( NULL, "()- " );
if ( p != NULL )
strncat ( number, p, sizeof number - 1 );
puts ( area );
puts ( number );
}
Converting the area code to an integer and the number to a long is pretty simple, but rather than do your homework for you, I'll leave it to you and a good reference to figure out. :) Here's one piece of advice though: don't use atoi, if there's an error during conversion then you'll invoke undefined behavior. The only way to avoid that is to thoroughly validate your input beforehand. strtol is a much better option.
-
-