Clear the cin buffer before another input request,

2019-08-02 14:29发布

问题:

I have the following code:

int choice = 0;
char st1[N];

cout << "enter choice" <<endl;
cin >> choice;

cout << "enter sentence" << endl;
cin.get(st1, N-1);

when getting to cin.get line, no matter what the input is, it will read \0 char into st1[0] and that's it.

I assume it has something to do with the latest cin ( into choice variable ).

How do i "clean" cin buffer before getting new input from the user? if that's possible.

thanks

回答1:

You might use ignore to drop the newline from the buffer (e.g. drop X characters before the newline as delimiter). Extraction and ignore stop when the delimiter is extracted.

e.g.

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

Also related: Why would we call cin.clear() and cin.ignore() after reading input?



回答2:

You could always try using cin.sync().



回答3:

Do a getchar() after cin >> choice;. This will consume the \n from the input buffer.

Since choice is of type int, the \n is left over in the buffer and when the string input is taken, this \n is encountered and it stops taking input there.



标签: c++ input cin