Reputation: 369
I'm trying something very simple; comparing a user inputted string to "hello" but strcmp does not want to work. I know I'm missing something obvious and I think it has to do with the way I declared my string. All help is greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
char command[4555], compare[] = "hello";
fgets (command, sizeof (command), stdin);
printf ("%s\n%s\n", command, compare);
if (strcmp (command, compare) == 0)
{
printf ("The strings are equal");
} else {
printf ("The strings are not equal");
}
}
Upvotes: 0
Views: 229
Reputation: 122
Well, just to add something, Yes fgets appends a '\n' char to the input string.
So, its better to use strncmp function which is also in the same library.
strncmp (command, compare,strlen(command)-1) .
It works fine.
Upvotes: 1
Reputation: 11
By using fgets you add a '\n' before the '\0' in your string. By using :
if(command[strlen(command)-1]=='\n')
command[strlen(command)-1]='\0';
You will delete it and effectively compare your strings
Upvotes: 1
Reputation: 27572
fgets
will leave the newline in the buffer and then null terminate while command will have no newline and just be null terminated.
Upvotes: 3