1

I have a simple code: If ch is Y, then the first if statement runs, if N, then the other, if anything else, then the else statement. But if I give more than one character, then it writes "wrong input" out many times. How can I solve this issue, so anything I write the else statement only runs once?

#include <iostream>

using namespace std;

int main()
{
    bool running = true;
    char ch;


    do{
        cout << "Enter Y or N: ";
        cin >> ch;
        cout << endl;
        if(ch == 'Y'){
            cout << "You entered yes." << endl;
            running = false;
        } else if(ch == 'N'){
            cout << "You entered no." << endl;
            running = false;
        } else{
            cout << "Wrong input." << endl;
        }
    }while(running);

    return 0;
}
Garf365
  • 3,619
  • 5
  • 29
  • 41
  • Possible duplicate of [Do-while endlessly looping cout, ignores cin](http://stackoverflow.com/questions/14907978/do-while-endlessly-looping-cout-ignores-cin) – Simon Kraemer Mar 14 '16 at 14:19

1 Answers1

0

What you need to do is clear the rest of the input stream to make sure on the next iteration you are waiting for new input and not reading input that was left in the buffer. We can use ignore for that like

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

You can either place it as the last line of the do loop so it clears the buffer for every case or you can add it to the last else statement.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402