Reputation: 149
The following loop acts like a lock, it only accepts certain user input values for the program to continue.
I want to exit the while loop when selection
has the either of the following values: "X"
,"x"
,"Y"
,"y"
. In the following I have programmed it to do so but when testing the code and entering those values, the loop does not stop instead it becomes a infinite loop. How do I fix this?
selection
is initialized as "O"
.
while( selection != "X" || selection != "x" || selection != "Y" || selection != "y"){
cin >> selection;
}
Upvotes: 0
Views: 72
Reputation: 2704
You can manually break the loop inside the while loop based on conditions, this is easier for beginners.
while( true){
cin >> selection;
if( selection == "X" || selection == "x" || selection == "Y" || selection == "y")
{
break;
}
}
Upvotes: 0
Reputation: 161
while( selection != "X" && selection != "x" && selection != "Y" && selection != "y"){
cin >> selection;
}
Since you were using the or(||) in order for that entire statement to evaluate to false all of the individual statements would need to be false. You need to use an and(&&) since then the entire statement would be false if even a single statement would be false. Hope this helped.
Upvotes: 1