views:

207

answers:

3

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.

[SOLVED]

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 if(cin.fail())
        {
          cin.clear()
          cin.ignore()
          cout << "Incorrect entry. Try again: ";
        }
    }
}
+1  A: 

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.

Brandon E Taylor
Yeah, I actually tried using cin.clear() to clear out the buffer but that didn't change anything. I will try your other suggestions though.
trikker
Checking for cin.fail() and using cin.ignore() and cin.clear() patched things up. Thanks.
trikker
+3  A: 

The is still a problem is you "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
}
AProgrammer
This is absolutely the right way to do it.
Tyler McHenry
But no matter how many times it is pointed out, people insist on doing it the wrong way. I've kind of given up on it :-(
anon
Thanks AProgrammer. I'll patch that in.
trikker
A: 

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

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