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

标签 c string fgets strcmp

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/

相关文章:

c++ - automake 的自动检测源

Java : Char vs String byte size

python - 类型错误: 'in <string>' 需要字符串作为左操作数,而不是列表(列表理解)

java - 文件行中的 bin 编号可以优雅地分组

c - 让 fgets 跳过特殊字符

C:打印的字符不正确,怀疑是内存。问题

计算数组大小

c++ - C 检查或转换指数

c++ - fgets 与 std::fgets - fgets 错过了行

c - 自纪元以来的秒数的星期几