while loop chars C++

14,210

Solution 1

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.

Solution 2

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.

Share:
14,210
beatlesfan42
Author by

beatlesfan42

Updated on June 27, 2022

Comments

  • beatlesfan42
    beatlesfan42 almost 2 years

    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();
        }
    
  • beatlesfan42
    beatlesfan42 almost 10 years
    Aaaaand, I feel like a dummy now. Literally the one thing I haven't checked. Thanks!
  • Erika
    Erika over 4 years
    thanks for this insight! been having this problem for quite a time now. thanks a lot!