gpt4 book ai didi

c - 为什么strcmp不返回0

转载 作者:行者123 更新时间:2023-11-30 20:09:24 26 4
gpt4 key购买 nike

在我的程序的这个迷你版本中,我要求用户输入。当输入为“退出”或“退出”时,我希望程序退出 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;
}

最佳答案

fgets 读取尾随的 \n 并将其存储在缓冲区中,因此您始终将 quitquit\进行比较n.

此外,在 while 循环第一次检查其条件时,可能会发生非常糟糕的事情,因为您的 request 数组未初始化。

关于c - 为什么strcmp不返回0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52652317/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com