【发布时间】:2020-02-13 22:20:39
【问题描述】:
这是我写的代码:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define SIZE 50
int main(int argc, char *argv[])
{
char str[SIZE];
char str2[] = "exit";
//fgets(str, sizeof str, stdin);
while (strcmp(str, str2) != 0)
{
fgets(str, sizeof str, stdin);
printf("%s", str);
}
return 0;
}
但它似乎没有退出并陷入无限循环。
【问题讨论】:
-
fgets返回的字符串将包含换行符 (\n)。尝试使用strncmp(str, str2, 4) != 0。 -
str第一次未初始化;也许使用不同的循环机制? -
@AdrianMole 匹配,例如,
exiting。 -
@Neil - 很好发现!