Search code examples
cstringfgetsstrcmp

C: Working with strcmp


As a beginner I've been playing around with some of the functions of the library string.h and have some issues regarding the function strcmp.

I wrote the program comparing two string. If they are equal it returns YES and NO otherwise.

#include <stdio.h>
#include <string.h>

int main() {

    char a[100];
    char b[15] = "hello";

    fgets(a, 100, stdin);

    int compare;

    compare = strcmp(a, b);

    if(compare == 0) {

        printf("YES");
    }
    else {

        printf("NO");
    }

    return 0;
}

After running it even when I input from the keyboard a hello I get a NO. When I add the line printf("%d", compare) it turns out that for any input I get a 1, that is, the stopping character in a is greater than the one in b.

Where is my mistake?


Solution

  • fgets appends the new line character corresponding to the Enter key if there is enough space in the source array.

    You should remove the character before comparing the string with another string the following way

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

    For example

    #include <stdio.h>
    #include <string.h>
    
    int main() {
    
        char a[100];
        char b[15] = "hello";
    
        fgets(a, 100, stdin);
    
        a[strcspn( a, "\n" )] = '\0';
    
        int compare;
    
        compare = strcmp(a, b);
    
        if(compare == 0) {
    
            printf("YES");
        }
        else {
    
            printf("NO");
        }
    
        return 0;
    }