1

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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Pedro Luiz
  • 33
  • 3
  • I forgot to salute and I'm trying to edit my post but I can't, so, hello everyone! – Pedro Luiz Oct 07 '22 at 15:18
  • "Good morning", "Hello everyone", "Thank" you etc. is not necessary here. Just ask your question. And upvote useful comments and answers. – Jabberwocky Oct 07 '22 at 15:45

2 Answers2

2

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;
}
CGi03
  • 452
  • 1
  • 3
  • 8
1

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335