JamesPoppycock JamesPoppycock - 1 year ago 60
C++ Question

c++ multiple condition to match exact string

I wish to look for exact match of the variable "check". If the user types "type o" or "type b", the loop will end. I tried

while (check != "type o"){...}
and it works, but not with a second condition. I am confused. Below is my code.

void sunTypeCheck(string sunCheck){
string check = sunCheck;

transform(check.begin(), check.end(), check.begin(), ::tolower);

while (check != "type o" || check != "type b"){ //This is the problem.
cout << "Please enter a valid type of Sun. Try again: ";
getline(cin, check);
transform(check.begin(), check.end(), check.begin(), ::tolower);

Here is my main method.

int main(){
cout << "Please enter sun type: ";
getline(cin, typeOfSun);

Any help will be greatly appreciated. I look online and tried using "compare" but as long as I included a second condition, it will not work, and program will always return
Please enter a valid type of Sun. Try again:

Answer Source

while loop breaks when the condition become false.

check != "type o" || check != "type b"

|| operator returns true when one of the conditions returns true and false if its both false.

so lets say you entered "type o" it will be like this:

"type o" != "type o" || "type o" != "type b"

the first condition returns false and the second will return true.

false || true

so what did i say when one of the condition of || operator returns true? yes, it will be true.

so to fix this you must use && operator

while(check != "type o" && check != "type b")

Edit: for && operator, it returns false when one of the condition is false and returns true if and only if both condition is true.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download