-3

I have a strcmp function as so:

if (strcmp(userInput, "Yes") == 0)

For some reason, it will not enter the if statement, even though I am sure the userinput definitely equals Yes. Anyone have any clue whats wrong?

AkshaiShah
  • 5,739
  • 11
  • 37
  • 45

4 Answers4

3
  1. Make sure you're including the proper header, i.e. <string.h>.
  2. If you're getting userInput from e.g. fgets(), make sure there's no line termination at the end, it will interfere with a comparison written like that.
unwind
  • 391,730
  • 64
  • 469
  • 606
2

To avoid troube with a tailing linebreak you could maybe check just the first 3 chars:

if(strncmp(userInput, "Yes", 3) == 0)
rekire
  • 47,260
  • 30
  • 167
  • 264
1

As is, your code is fine. That is not the problem.

I suspect you're doing this:

fgets(userInput, sizeof(userInput), stdin);
if(strcmp(userInput, "Yes") == 0)

Which is giving you a newline char:

['Y']['e']['s']['\n']

You can fix that any number of ways:

if(strcmp(userInput, "Yes\n") == 0)

Is probably the easiest. Or you could get input via scaf:

scanf("%s", userInput);
Mike
  • 47,263
  • 29
  • 113
  • 177
0

You can typecast if you need help.

//I am assuming usrInput is a char Array

string str(usrInput);
//string class has a constructor that takes a NULL-terminated C-string
if (str == "Yes")
{
   //do what ever you wanted to in the loop
}
crh225
  • 821
  • 18
  • 34