Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while loop chars C++

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();
    }
like image 981
beatlesfan42 Avatar asked Feb 04 '26 05:02

beatlesfan42


1 Answers

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.

like image 168
vsoftco Avatar answered Feb 05 '26 19:02

vsoftco