C 我如何使其正确退出程序?

C 我如何使其正确退出程序?,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) {

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

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

键盘输入的末尾包含一个新行。将调用中的
strcmp
中的
“exit”
更改为
“exit\n”

您在
状态中声明了一个新的
x
变量。那是行不通的
x
已经声明。@RobertHarvey是的,我只是在网站上键入了错误的代码,打开后仍然存在。如果您只是将代码复制/粘贴到堆栈溢出中,而不是尝试重新键入代码,效果会更好。
fgets
在出现读取错误时可能会返回NULL,因此这不是一个安全的用法请记住fgets存储每个你输入的字符。按Enter键后,它将停止,但此时它已存储Enter字符。
//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)//