Annoying problem when checking user input

So the simple program below asks the user to enter an integer greater than ro equal to 0. If the user enters in a negative integer or a character (a letter, dot, dash etc..), the buffer clears, the invalid input is ignored and the message is repeated. This continues as long as the number entered is negative or the something other than an integer is entered.

The problem is, if multiple character are entered, the message is also repeated multiple times. How can one fix this so that no matter how many characters are entered the message only repeats once?

For example: If the user enters the characters 'fg/ab', I want the "Enter an integer zero or greater: " message to be only repeated once and NOT 5 times like it does here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using namespace std;

int main()
{
    int a;

    cout << "Enter an integer zero or greater: " << flush;
    cin >> a;
    while(a<0 || !cin)
    {
        cin.clear();
        cin.ignore();
        cout << "Enter an integer zero or greater: " << flush;
        cin >> a;
    }

cout << "You entered " << a << endl; 

   cin.get();

}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using namespace std;

int main()
{
    int a;

    cout << "Enter an integer zero or greater: " << flush;
    cin >> a;
    while(a<0 || !cin)
    {
        cout << "Enter an integer zero or greater: " << flush;
        cin.clear();
        cin.ignore(10000, '\n');
        cin >> a;
    }

cout << "You entered " << a << endl;

   cin.get();

}
Can you briefly explain why adding those two parameters to cin.ignore() solves this problem?

for example, why wouldn't cin.ignore(1000) work? (i.e. without the newline character)

I would really appreciate it.

EDIT: Never mind. Figured it out.
Last edited on
Topic archived. No new replies allowed.