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

Clearing buffer

dev7060
P: 66
[Screenshot 1] The screen is not stopping on cin.get() functions for the user to input something. Maybe automatically taking the "enter key" from the buffer.
[Screenshot 2] On using some functions to clear the buffer (like cin.ignore() and fflush(stdin) ), everything is working as required.

My questions are:
(If I am getting something wrong, please point out)

-Why does cin.get() automatically taking the "enter key" from the buffer (previous inputs)?
- Why do simple implementations of cins not follow this thing?
Like:
Expand|Select|Wrap|Line Numbers
  1. cout<<"enter something"; cin>>a;
  2. cout<<"enter something"; cin>>b;
  3. cout<<"enter something"; cin>>c;
  4.  // Here the screen stops everytime
-Are these functions (of clearing buffers) especially designed for such cases? Could you provide an example scenario where we don't need those functions? I mean why would someone want to access the previous buffer data of "enter key".
Attached Images
File Type: jpg 1.jpg (100.1 KB, 33 views)
File Type: jpg 2.jpg (127.4 KB, 78 views)
Sep 18 '18 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
I don't see any error checking here. How do you know the cin>> worked?

If it gets an error, the data is left in the buffer and the cin>> quits. The next cin>> sees the error and bails without even trying.


This makes it appear all the cin>> quit working for the rest of the program.

Maybe something like this:

Expand|Select|Wrap|Line Numbers
  1. bool GetInt(int* data)
  2. {
  3.     cin >> *data;
  4.     if (cin.good())
  5.     {
  6.       return true;
  7.     }
  8.     else
  9.     {
  10.         cin.clear();
  11.         _flushall();  //Microsoft only
  12.         return false;
  13.     }
  14. }
Sep 18 '18 #2

Post your reply

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