Clear the cin buffer before another input request, c++

时间秒杀一切 提交于 2019-12-24 05:47: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.



来源:https://stackoverflow.com/questions/23713346/clear-the-cin-buffer-before-another-input-request-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!