IF statements that feature strings with the != operator.

Trying to write an IF statement that compares a string that contains user input with a group of specified characters framed by quotation marks (such as "y" || "Y" etc.).

Here is the code:

1
2
3
4
5
6
7
8
9
10

string a;

cout << "Use main settings?" << endl;
cin >> a;

if(a != "y" || "Y")
{
execute this code...
}


However, the code in the if statement always seems to execute regardless of user-input.

The statement become sensitive to user-input when I use '==' instead of '!=' though I'm not sure why that is.

Can anyone explain how to correct this problem?
 
if (a != "y" || a != "Y")

However, keep in mind that the condition (a != "y" || a != "Y") is true for all possible values of a.

If a = "y":
(a != "y" || a != "Y") = (false || true) = true

If a = "Y":
(a != "y" || a != "Y") = (true || false) = true

If a = "snafu":
(a != "y" || a != "Y") = (true || true) = true

You probably want (a != "y" && a != "Y").
Topic archived. No new replies allowed.