解决 strtok While 循环中断外部 while 循环问题



如果我删除strtok的while循环,外部while循环可以继续,直到我键入exit。但是外部的 while 循环与内部的 strtok 循环中断。我想知道为什么会这样。

#include <stdio.h>
#include <stdlib.h> // For exit() function
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <memory.h>
#include <stdlib.h>
int main()
{
char input[1024];
fgets(input,1024,stdin);
do
{
printf("%sn",input);
char* token = strtok(input, " ");
while (token) {
printf("%sn", token);
token = strtok(NULL, " ");
}
fgets(input,1024,stdin);
}while (strcmp(input, "exitn") == 1);
return 0;
}

而不是这些语句

fgets(input,1024,stdin);
}while (strcmp(input, "exitn") == 1)

写以下内容

}while ( fgets(input,1024,stdin) != NULL && strcmp(input, "exitn") != 0 );

如果两个字符串不相等,函数strcmp可以返回任何非零值。

最新更新