int main()
{
int n = 100;
char a[n];
char b[ ]="house";
fgets(a,n-1,stdin); // type "house"
if (strcmp(a,b) == 0)
printf("The strings are equal.\n");
else
printf("The strings are not equal.\n");
return 0;
}
最佳答案
这是为什么
if (strcmp(a,b) == 0) { }
不正确,因为 fgets()
将 \n
存储在缓冲区的末尾。所以这里的数组 a
看起来像 house
而数组 b
看起来像 house\n
(如果 ENTER
键在输入字符后被按下)并且 strcmp(a,b)
不返回 0
。
来自 fgets()
fgets()
reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.
一种方法是使用 strcspn()
删除尾随的 \n
。例如
fgets(a,n,stdin);
a[strcspn(a, "\n")] = 0;
现在比较一下char数组
if (strcmp(a,b) == 0) {
printf("The strings are equal.\n");
}
else {
printf("The strings are not equal.\n");
}
关于c - 为什么看起来字符串不相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53857550/