Search code examples
cnewlinec-stringsfgetsstrcmp

How to compare two char arrays in C?


I'm coming from Python and there you can easily compare two strings (char arrays) like that:

if "foo" == "bar":
    # ...

How would I do this in C? I already saw this post but it didn't work.

Code:

int main(void) {

    char string[100];
    
    printf("Please enter something: ");
    fgets(string, 100, stdin);

    if (strcmp(string, "a") == 0)
        printf("a");

    else if (strcmp(string, "b") == 0)
        printf("b");

    else if (strcmp(string, "c") == 0)
        printf("c");

    else
        printf("something else");


    return (0);
}

It prints "something else" though I entered a.


Solution

  • The function fgets can append to the entered string the new line character '\n' that you should remove. For example

    fgets(string, 100, stdin);
    string[ strcspn( string, "\n" ) ] = '\0';
    

    or

    fgets(string, 100, stdin);
    char *p = strchr( string, '\n' );
    if ( p != NULL ) *p = '\0';
    

    From the C Standard (7.21.7.2 The fgets function)

    2 The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.