c++ – Clearing the cin input buffer

Question:

Hello. There is a code.

char friend_sex = 0;

//check if sex is valid
bool ok_sex = false;
//---------------------

while (!ok_sex){

    cout << "Enter the sex of your mutual friend\n";

    // What is sex of that person?
    cout << "M or W: \n";
    //----------------------------

    cin >> friend_sex;

    if(friend_sex == 'M' || friend_sex == 'W'){

        ok_sex = true;

    }

}

I am just learning C ++ and want to do some handling of wrong gender input of friend. For example, the user enters something other than W and M and the request for an introduction is repeated in a loop, as can be seen from the code. This will also happen if the user enters many characters instead of one. But there is one point. The fact is that since the type of the variable is friend_sex char, the sequence of characters is read from the input stream character by character. I wrote abcd , let's say, but first a was counted, then (if it is in a loop, the second character is taken and a check occurs, and so on until the end). In fact, if you write abcMf , then on checking the fourth character, the cycle will end, because the test will be passed.

Question: I want that when I enter a sequence of characters, the first one is read and the input buffer is cleared of the rest. Please advise the function to clear the buffer (cin.clear () does not work).

Answer:

Try it

cin.clear(); // на случай, если предыдущий ввод завершился с ошибкой
cin.ignore(numeric_limits<streamsize>::max(), '\n');

Do not forget

#include <iostream>
#include <limits>
Scroll to Top