简体   繁体   中英

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

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

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

eg

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

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

您总是可以尝试使用cin.sync()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM