Search code examples
cstringfgetsstrcmp

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

Solution

  • 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");
    }