gpt4 book ai didi

c - 解决strtok While循环打破外层while循环问题

转载 作者:行者123 更新时间:2023-11-30 16:05:50 25 4
gpt4 key购买 nike

如果我删除 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("%s\n",input);
char* token = strtok(input, " ");
while (token) {
printf("%s\n", token);
token = strtok(NULL, " ");
}
fgets(input,1024,stdin);
}while (strcmp(input, "exit\n") == 1);
return 0;
}

最佳答案

代替这些语句

    fgets(input,1024,stdin);
}while (strcmp(input, "exit\n") == 1)

写出以下内容

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

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

关于c - 解决strtok While循环打破外层while循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60159347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com