Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User Input of Integers - Error Handling

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: ";
    }
}
like image 269
trikker Avatar asked Aug 16 '09 01:08

trikker


People also ask

How do you take user input in integer?

Use Python built-in input() function to take integer input from the user. This input() function returns string data and it can be stored in a string variable. Then use the int() function to parse into an integer value.

How do I make sure user input is int in C++?

Input the data. Apply isdigit() function that checks whether a given input is numeric character or not. This function takes single argument as an integer and also returns the value of type int.


1 Answers

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
}
like image 133
AProgrammer Avatar answered Oct 30 '22 14:10

AProgrammer