Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
strcmp为什么不返回0_C_Strcmp - Fatal编程技术网

strcmp为什么不返回0

strcmp为什么不返回0,c,strcmp,C,Strcmp,在我的程序的这个小版本中,我请求用户输入。当输入为“退出”或“退出”时,我希望程序退出while循环。strcmp功能似乎没有像我预期的那样工作。我花了一些时间寻找答案,但找不到问题所在。有什么想法吗 #include <stdlib.h> #include <stdio.h> #include <string.h> #define BUFFER_SIZE 100 int main() { char request[BUFFER_SIZE];

在我的程序的这个小版本中,我请求用户输入。当输入为“退出”或“退出”时,我希望程序退出while循环。strcmp功能似乎没有像我预期的那样工作。我花了一些时间寻找答案,但找不到问题所在。有什么想法吗

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define BUFFER_SIZE 100
int main() {
    char request[BUFFER_SIZE];
    while(strcmp(request, "quit") != 0 && strcmp(request, exit) != 0) {
        fgets(request, BUFFER_SIZE, stdin);
    }
    return 0;
}
#包括
#包括
#包括
#定义缓冲区大小为100
int main(){
字符请求[缓冲区大小];
while(strcmp(请求,“退出”)!=0和strcmp(请求,退出)!=0){
fgets(请求、缓冲区大小、标准输入);
}
返回0;
}

fgets
读取尾随的
\n
并将其存储在缓冲区中,因此您总是将
quit
quit\n
进行比较


同样在
循环第一次检查其状态时,可能会发生非常糟糕的事情,因为
请求
数组未初始化。

fgets
读取输入时,它也会读取输入端的换行符,如果有足够的空间存储该换行符。这意味着,如果您输入“退出”,那么请求实际上将包含“退出\n”

而且,第一次通过循环时,
request
不包含任何内容,因此您正在读取未初始化的值

在这种情况下,最简单的方法是将换行符添加到要检查的字符串中,并将
while
循环更改为
do..while
循环,以便在末尾执行检查:

do {
    fgets(request, BUFFER_SIZE, stdin);
} while(strcmp(request, "quit\n") != 0 && strcmp(request, "exit\n") != 0);

另请注意,您在第二次调用中传递的是函数
exit
,而不是字符串
“exit”

后面有一个
\n
。另外,第一个循环包含UB。请注意,
strcmp(request,exit)
正在将
exit()
函数的函数指针与
request
进行比较-这不好。您可能是指strcmp(请求,“退出”)
。请注意编译器警告,并在提出问题之前修复它们。如果你不明白,也可以询问警告。