gpt4 book ai didi

c - fgets() 在末尾包含换行符

转载 作者:行者123 更新时间:2023-11-30 16:38:44 24 4
gpt4 key购买 nike

fgets(input,sizeof(input),stdin);
if (strcmp(input, "quit") == 0){
exit(-1);
}

如果我输入 quit,它不会退出程序;我想知道为什么会出现这种情况。

顺便说一句input声明为char *input; .

最佳答案

函数fgets可能会在读取的字符串末尾添加换行符。您必须检查:

size_t ln = strlen(input) - 1;
if (input[ln] == '\n')
input[ln] = '\0';

甚至

strtok(input, "\n");

关于c - fgets() 在末尾包含换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47381071/

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