user2929779
user2929779

Reputation: 369

I can't seem to get strcmp working correctly

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

Answers (3)

Rafed Nole
Rafed Nole

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

Eiles
Eiles

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

Duck
Duck

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

Related Questions