Stack Overflow Asked by iSythnic on December 22, 2021
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;
}
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;
}
}
Answered by Ahmad Anis on December 22, 2021
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.
Answered by Alex on December 22, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP