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?
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?
<string.h>
.userInput
from e.g. fgets()
, make sure there's no line termination at the end, it will interfere with a comparison written like that.To avoid troube with a tailing linebreak you could maybe check just the first 3 chars:
if(strncmp(userInput, "Yes", 3) == 0)
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);
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
}