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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.