Help with strcmp function in C

I am trying to compare strings in C with the following code

int strcmp ( const char * str1, const char * str2 );


int main()
{
    char name[10];
   fgets(name,10,stdin);

if (strcmp(name, "Tom") == 0)
{
    printf("Hi, Tom!");
}
else{
    printf("You're not Tom!");
}

    return 0;
}

However, it will always print “You’re not Tom!” even when I input “Tom” which is confusing. Did I make a mistake?

What is this? You should need an import to get this function.

1 Like

I see two problems here:

  1. As @JeremyLT says, there’s no #include for the string library in the code you’re displaying. What that means is you’re (potentially) aliasing the strcmp function with garbage (since you’re not providing a strcmp definition). But if the code is compiling and running, this is unlikely.

  2. You’re calling fgets incorrectly. fgets expects a char * as the first argument, and that’s not what you’re passing in. So you’re comparing “Tom” to whatever garbage happens to be in memory starting at name[0]. Try calling fgets(&name,…)

jrm

Hi sorry, I’m not really familiar with C, but when I google stuff out, some forums say that I should be using a function like that so I tried running it, and the result is as shown. I’m still new to C so I haven’t gotten to importing stuff yet