Search code examples
c++linuxunixstreamistream

How to clear cin buffer after reading char


I have one problem. Firstly I need to read one character from user input after that I need to read integer. The problem is that if I enter more than one char on first cin, it doesn't request to enter integer value.
Here is snippet of my code.
Is there any function to reset or clear buffer of cin.
I am newbie, sorry if the question is stupid. Thanks.

int *i = new int;
int *c = new char;
std::cin >> *c;
std::cin >> *i;

Solution

  • You asked:

    Is there any function to reset or clear buffer of cin.

    There is std::istream::ignore(). There is example code at the given link which shows how to use the function.

    In your case, I see something like:

    int i;
    int c;
    std::cin >> c;
    std::cin >> i;
    
    if (std::cin.bad()) {
       std::cin.clear(); // unset failbit
       std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip bad input
       std::cin >> i;
    }