clear buffer code example

Example 1: 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
}

Example 2: c clear buffer

void clearBuffer() {
	char c;
	do {
		c = getchar();
	} while (c != '\n' && c != EOF);
}

Tags:

Cpp Example