Clear the cin buffer before another input request,

2019-08-02 14:38发布

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

标签: c++ input cin
3条回答
干净又极端
2楼-- · 2019-08-02 14:57

You could always try using cin.sync().

查看更多
Juvenile、少年°
3楼-- · 2019-08-02 15:06

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?

查看更多
Fickle 薄情
4楼-- · 2019-08-02 15:08

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.

查看更多
登录 后发表回答