这是我的代码:
printf("Please input a command\n");
char *input;
input = malloc(sizeof(char) * 50);
if(fgets(input, 50, stdin) != NULL) {
if(strcmp(input, "end\0") == 0) {
printf("END");
}
}
由于某种原因,当我输入“end”时,它不会打印“END”。这里导致循环条件失败的问题是什么? strcmp(input, "end\0") == 0
当输入指针等于 "end\0"
时应返回 0 ?我也尝试过strcmp(input, "end") == 0
这也行不通。我该如何解决这个问题?
最佳答案
fgets
包括换行符。使用strcmp(input, "end\n")
来自文档:
Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.
A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.
正如评论中提到的,您不需要包含 \0
当使用字符串文字时。将自动添加空终止符。
关于c - 使用函数 strcmp 比较指针和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47857697/