我正在尝试从文件中提取电话号码并将其打印出来
输入
my number is (123) 456-7897 ok, my other number is (654) 393-3030 buddy.
我的变量是
char *last_token;
char *firstpart;
char buffer[BUFFER_SIZE];
char *phoneNumber;
这是我当前的循环
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");
}
}
应该打印
(123) 456-7897
(654) 393-3030
而是打印
(123)
(654)
我猜测字符串在之后被终止了,但我无法弄清楚为什么
答案 0 :(得分:1)
strcat(phoneNumber, " ");
使用'\0'
将其重写为last_token
的开头。
char phoneNumber[15];
...
strcpy(phoneNumber, firstpart);
strcat(phoneNumber, " ");
strcat(phoneNumber, last_token);
printf("%s\n", phoneNumber);