为什么看起来字符串不相等?

Why does it seem like the strings are not equal?

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;
}

在您的示例中,这就是 strcmp 正在比较的内容

strcmp("house\n", "house")

这是错误的。

这是一个您可以添加的解决方案,用于将您的代码修复为(我假设)您期望它工作的方式。

int main()
{
    int n = 100;
    char a[n];
    char b[] = "house";
    fgets(a, n-1, stdin);
    a[strlen(a) - 1] ='[=11=]';  //you may want to add length checking to prevent errors if user input is null
    if (strcmp(a, b) == 0)
        printf("The strings are eq\n");
    else
        printf("Not eq\n");
    return 0;
}

这是为什么

if (strcmp(a,b) == 0) { }

不正确,因为 fgets()\n 存储在缓冲区的末尾。所以这里数组 a 看起来像 house,数组 b 看起来像 house\n(如果在输入字符后按下 ENTER 键)和 strcmp(a,b)没有 return 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 ('[=26=]') 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");
}