Search code examples
cnewlinec-stringsfgetsstrcmp

Compare arrays with different sizes with strcmp()


I'm currently learning C and I have this question...

char name[6] = "Pedro";
char test[25];

printf("Insert a name: ");
fgets(test, 25, stdin);

if(!strcmp(name, test))
   puts("They are equal...");

During the execution, strcmp doesn't return 0 when I insert the value "Pedro" in the array "test"... I know the array "test" have a size of 25 instead of 6, but since C dettects the end of a string with '\0', how can I use the fgets in this situation?

Thank you very much...


Solution

  • The function fgets can append to the entered sequence of characters the new line character '\n' that corresponds to the pressed key Enter.

    You need to remove it before calling strcmp like for example

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

    Pay attention that it will be more safer to write

    char name[] = "Pedro";
    

    instead of

    char name[6] = "Pedro";
    

    Otherwise in general you can make a mistake counting characters in a string literal.

    Also instead if this line

    fgets(test, 25, stdin);
    

    it will be better to write

    fgets(test, sizeof( test ), stdin);
    

    without using the magic number 25.