Catch cin exception

Luca Thiede

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?

Sergey Kalinichenko

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related