strcat(phoneNumber, " ");
this was rewritten with '\0'
to the beginning of the last_token
.
char phoneNumber[15];
...
strcpy(phoneNumber, firstpart);
strcat(phoneNumber, " ");
strcat(phoneNumber, last_token);
printf("%s\n", phoneNumber);
문제
I am trying to extract a the phone numbers from the a file and print them out
Input
my number is (123) 456-7897 ok, my other number is (654) 393-3030 buddy.
My variables are
char *last_token;
char *firstpart;
char buffer[BUFFER_SIZE];
char *phoneNumber;
Here is my current loop
while( fgets(buffer, BUFFER_SIZE, input) != NULL ){
last_token = strtok( buffer, " \n" );
while(last_token != NULL) {
//see if first part of number is correct
if(*last_token == '(' && isdigit(*(last_token + 1)) && isdigit(*(last_token + 2)) && isdigit(*(last_token + 3)) && *(last_token + 4) == ')' && *(last_token + 5) == '\0') {
firstpart = last_token; //if it is save it
last_token = strtok(NULL, " \n"); //check next part
//if second part is also correct
if (isdigit(*last_token) && isdigit(*(last_token + 1)) && isdigit(*(last_token + 2)) && *(last_token + 3) == '-' && isdigit(*(last_token + 4)) && isdigit(*(last_token + 5)) && isdigit(*(last_token + 6)) && isdigit(*(last_token + 7)) && *(last_token + 8) == '\0') {
phoneNumber = firstpart; //set phone number to first part
strcat(phoneNumber, " "); //add a space to phone number
strcat(phoneNumber, last_token); //add the last part of the phone nmber
printf("%s\n", phoneNumber); //print the number
}
}
last_token = strtok(NULL, " \n");
}
}
It should be printing
(123) 456-7897
(654) 393-3030
But instead its printing
(123)
(654)
Im guessing that the string is getting terminated after the ) but I can't figure out why
해결책
strcat(phoneNumber, " ");
this was rewritten with '\0'
to the beginning of the last_token
.
char phoneNumber[15];
...
strcpy(phoneNumber, firstpart);
strcat(phoneNumber, " ");
strcat(phoneNumber, last_token);
printf("%s\n", phoneNumber);