c++ clear cin input buffer code example

Example: how to clear cin buffer

int number;

cout << "Enter an Integer: ";
cin >> number;

// User types any char or string of length < 100

// Because input stream is in a failed state, cin will be evaluated to false
while ( !cin )
{
    cin.clear ();    // Restore input stream to working state
    cin.ignore ( 100 , '\n' );    // Get rid of any garbage that user might have entered
    cout << "I said enter an integer, Dumbass. Try again: ";
    cin >> number;    // After cin is restored and any garbage in the stream has been cleared, store user input in number again
}

Tags:

Cpp Example