首页 > 解决方案 > 为什么看起来字符串不相等?

问题描述

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

标签: cstringfgetsstrcmp

解决方案


Reason why this

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

is not true because fgets() stores the \n at the end of buffer. So here array a looks like house and array b looks like house\n(If ENTER key was pressed after entering input char's) and strcmp(a,b) doesn't return 0. From the manual page of 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.

One way is to use strcspn() which removes the trailing \n. For e.g

fgets(a,n,stdin);
a[strcspn(a, "\n")] = 0;

Now compare the char array like

if (strcmp(a,b) == 0) {
        printf("The strings are equal.\n");
}
else {
        printf("The strings are not equal.\n");
}

推荐阅读