User Input of Integers - Error Handling

2020-02-01 02:56发布

问题:

I'm having some trouble with certain input areas of my program. There are a few parts where the user inputs a specific integer. Even if they enter the wrong one that's all fine and dandy, but I noticed if they enter anything not of integer type like 'm' then it will loop the error message repeatedly.

I have a couple functions that have integer input in them. Here's one for an example.

void Room::move(vector<Room>& v, int exone, int extwo, int exthree, int current)
{
    v[current].is_occupied = false;
    int room_choice;
    cout << "\nEnter room to move to: ";
    while(true)
    {
        cin >> room_choice;
        if(room_choice == exone || room_choice == extwo || room_choice == exthree)
        {
            v[room_choice].is_occupied = true;
            break;
        }
        else cout << "Incorrect entry. Try again: ";
    }
}

回答1:

You can use cin.good() or cin.fail() to determine whether cin could successfully deal with the input value provided. You can then use cin.clear(), if necessary, to clear the error state before continuing processing.



回答2:

There is still a problem in your "solved" code. You should check for fail() before checking the values. (And obviously, there is the problem of eof() and IO failure as opposed to format problems).

Idiomatic reading is

if (cin >> choice) {
   // read succeeded
} else if (cin.bad()) {
   // IO error
} else if (cin.eof()) {
   // EOF reached (perhaps combined with a format problem)
} else {
   // format problem
}


回答3:

For a even simpler way, you can use ! operator like this:

        if ( !(cin >> room_choice) )
        {
          cin.clear();
          cin.ignore();
          cout << "Incorrect entry. Try again: ";
        }