Search code examples
c++stringfunctionif-statementstdstring

If statement incorrectly reads string, always returns on first condition


I'm writing an error-checking function that takes a string variable, and I need it to be one of "Y", "N", "y", or "n". My problem is that the string variable always gets set to "y", indicating that the if statement doesn't get past the first condition, no matter what input the variable receives. If there is an obvious error such as in my use of the '||' operator it would help me a lot if someone could let me know.

if (string == "y" || "Y") { //If 'yes'...
    string = "y"; //Standardise input for later use
    return 1; //Error check successfully passed
}
else if (string  == "n" || "N") { //If 'no'...
    string = "n"; //Standardise input for later use
    return 1; //Error check successfully passed
}
else { //If erroeneous input...
    return 0; //Error check not passed
} 

Solution

  • string == "y" || "Y" doesn't do what you think it does: it compares string against "y", and then ORs the result of that with "Y". Since "Y"' is non-zero, it always evaluates totrue`.

    The correct code is:

    string == "y" || string == "Y"