Reputation: 39
I'm working on a Programming assignment and I can't figure out why this while loop is looping infinitely. There has been other input before this loop occurs, but I have cin.ignore() to clear any junk out before this loop. I'm scratching my brain, help?
//Prompt for readiness
char ready = 'x';
while (ready != 'Y' || ready != 'y') {
cout << "READY TO START YOUR TURN " << playerName << "? ";
ready = cin.get();
}
Upvotes: 3
Views: 18191
Reputation: 3209
think of boolean algebra. OR gate results in true if one or both sides are true. so, if you input 'y'
or 'Y'
, your statement will result in returning true, since of the sides would still be true.
if you change ||
to &&
(AND gate), which returns true only if both of the sides are true, then your statement makes sense. user inputs 'y'
or 'Y'
(he's ready, so get him out of that loop!) and one of the sides is equal to false, hence loop terminates.
while (ready != 'Y' && ready != 'y') {
or
while (ready == 'Y' || ready == 'y') {
are statements that you meant.
Upvotes: 3
Reputation: 2464
change the code to this -
char ready = 'x';
while (ready != 'Y' && ready != 'y') {
cout << "READY TO START YOUR TURN " << playerName << "? ";
ready = cin.get();
}
It will resolve your issue.
Upvotes: 0
Reputation: 56557
You need to change ||
(OR) to &&
(AND). Also, reset the stream after you read with cin.get()
, i.e. put the following line after:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.clear();
(you need to #include <limits>
)
Otherwise, cin.get()
returns a char
and leaves an extra \n
(newline) in the stream, that gets read once more and you basically end up with the loop executing twice for each non-yes response.
Upvotes: 6