Home > Enterprise >  Compare arrays with different sizes with strcmp()
Compare arrays with different sizes with strcmp()

Time:10-08

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...

CodePudding user response:

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.

CodePudding user response:

fgets keeps the '\n' at the end of the line, it must be removed before the comparison. Example:

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

int main(void)
{
    char name[6] = "Pedro";
    char test[25];

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

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

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

    return 0;
}
  • Related