954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Clearing the input buffer

I am using cin to input a single character from keyboard.The problem is that if 2 or more characters are entered then the rest of the characters are being considered as input for the further cin statements.Is there any way in which I can clear the inpu buffer memory after every cin statement so that rest of the characters are removed from the buffer.

Eg.

char ch;
cout<<"\nInput a character:";
cin>>ch;
cout<<"\nInput another character:";
cin>>ch;


In the above example if two characters are entered at the first instance then the second character is considered as the input for the second cin statement.
I have tried using flush(), eof() and ignore() to no effect.
How to avoid this?Any help is highly appreciated.

bugmenot
Posting Whiz in Training
225 posts since Nov 2006
Reputation Points: 53
Solved Threads: 34
 

Read Narue's post

Also, it may be more beneficial for you to ignore a specified amount of characters or ignore characters until a specified delimiter is met--

#include <iostream>

using std::cin;
//...

int main(){

    //...
    cin.ignore(INT_MAX, '\n');

    return 0;
}


If you put cin in an error-state, you will have to pull it out of its error-state first before attempting to ignore characters. Another example of ignore

Alex Edwards
Posting Shark
972 posts since Jun 2008
Reputation Points: 392
Solved Threads: 109
 

http://www.daniweb.com/forums/thread90228.html

Look at this thread. It's a sticky (permanent) thread at the top of the opening page of this board/forum.

Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You