c - 我如何才能正确退出程序?

标签 c

所以我试图让这个程序简单地退出,但我似乎可以让它工作。

我尝试了很多事情。我还发现奇怪的一件事是,如果我在 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/

相关文章:

c - 如何验证c中的数值?

c - 重新分配指针?

c - 为什么那些打印相同的结果?

c - 如何从 C99 函数声明中确定返回类型、参数、函数名

c - PetscMalloc 与 PetscMallocX

c - 在 c 中使用 '??=' 、 '??<' 和 '??>'

c - 在这种情况下,char[] 和 char* 有何不同?

c - 如何使用 fdopen() 和 getline() 检查 HTTP 客户端的 EOF

在 linux 中创建一个守护进程

c - 从文件中读取整数并将其存储到数组中并写入文件