Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading