所以我试图让这个程序简单地退出,但我似乎可以让它工作。
我尝试了很多事情。我还发现奇怪的一件事是,如果我在 while 循环中设置 x = 0,它会立即退出程序,所以我必须使其 x !=0。我不明白那是什么,所以如果你也能回答的话那就太好了。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char a[256];
int x = 0;
while (x != 0) {
int y = strcmp(fgets(a, 256, stdin), "exit");
if (y==0) {
exit(0);
}
else {
printf("Line read:%s\n",a);
}
}
return 0;
}
所以它现在应该输出类似这样的内容(我也在 Linux 终端中运行它):
//input://
hello
//output://
Line read: hello
//(program stays open for more inputs)//
//input//
exit
//(the program now closes in the terminal and you return to directory)//
最佳答案
键盘输入末尾包含一个新行。在对 strcmp
的调用中将 "exit"
更改为 "exit\n"
。
关于c - 我如何才能正确退出程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58513855/