Clearing buffer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dev7060
    Recognized Expert Contributor
    • Mar 2017
    • 656

    Clearing buffer

    [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:
    Code:
    cout<<"enter something"; cin>>a;
    cout<<"enter something"; cin>>b;
    cout<<"enter something"; cin>>c;
     // 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 Files
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    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:

    Code:
    bool GetInt(int* data)
    {
        cin >> *data;
    	if (cin.good())
    	{
    	  return true;
    	}
    	else
    	{
    		cin.clear();
    		_flushall();  //Microsoft only
    		return false;
    	}
    }

    Comment

    Working...