User Input of Integers - Error Handling

后端 未结 3 1116
感动是毒
感动是毒 2020-12-03 15:47

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

相关标签:
3条回答
  • 2020-12-03 16:23

    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
    }
    
    0 讨论(0)
  • 2020-12-03 16:34

    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.

    0 讨论(0)
  • 2020-12-03 16:35

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

            if ( !(cin >> room_choice) )
            {
              cin.clear();
              cin.ignore();
              cout << "Incorrect entry. Try again: ";
            }
    
    0 讨论(0)
提交回复
热议问题