Luca Thiede
Luca Thiede

Reputation: 3453

Catch cin exception

I want to ask the user for input, which I get with cin like this

void AskForGroundstate() {
    cout << "Please enter an groundstate potential value in Volt:" << endl;
    if (!(cin >> _VGroundstate)) {
        cin.clear();
        cin.ignore();
        cout << "Groundstate potential not valid." << endl;
        AskForGroundstate();
    }
}

_VGroundstate is a double, so if the user enters an String with not numbers, it should ask him again for a better input. But the problem is, that when the input is for example "AA", than the program executes AskForGroundstate two times, with "AAA" three times etc. Did I use the clear wrong?

Upvotes: 2

Views: 330

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

The problem is that cin.ignore() drops one character; you want to drop all characters to end of line:

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

This ensures that all invalid input is dropped before end-users are prompted for input again.

Upvotes: 4

Related Questions