By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,530 Members | 880 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 428,530 IT Pros & Developers. It's quick & easy.

C++ flush input buffer correctly, not a question

P: 1
This is one of those extremely simple problems that no one knows how to do properly it seems. The most effective and efficient way to do this is to call ignore with the exact number of characters in the input buffer. It is sad to see people being called noobs from others who obviously have not taken the time to discover the best answer when its lying under their noses. Not that flushing the cin buffer is a big deal, but why bother acting elitist if you don't actually know what you are doing, I'd rather have a noob then someone who codes with bad habits, just saying.

cin.clear(); //clear errors/bad flags on cin

cin.ignore(cin.rdbuf()->in_avail(), '\n');//precise //amount of ignoring

cin.rdbuf()->in_avail() returns the exact number of characters in the cin buffer.

This is the best answer for a few reasons:

No clunky includes.
No giant number processing.
Required operations closer to the input buffer (in_avail vs. numeric_limits).
Consistency in following input operations (wont read past the "delimiter(\n)", or leave characters in the buffer).
Recommended by a c++ language lawyer, Dr Robert Johnson.
May 6 '16 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.