C++ 整数的用户输入 - 错误处理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1283302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
User Input of Integers - Error Handling
提问by trikker
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.
我在程序的某些输入区域遇到了一些问题。用户输入特定整数的部分有几个部分。即使他们输入了错误的,也很好,但我注意到如果他们输入任何非整数类型的东西,比如“m”,那么它会重复循环错误消息。
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: ";
}
}
回答by AProgrammer
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).
您的“已解决”代码中仍然存在问题。在检查值之前,您应该检查 fail()。(显然,与格式问题相反,存在 eof() 和 IO 失败的问题)。
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
}
回答by Brandon E Taylor
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.
您可以使用cin.good()
或cin.fail()
来确定 cin 是否可以成功处理提供的输入值。cin.clear()
如有必要,您可以在继续处理之前使用清除错误状态。
回答by Z.Zen
For a even simpler way, you can use !
operator like this:
对于更简单的方法,您可以使用这样的!
运算符:
if ( !(cin >> room_choice) )
{
cin.clear();
cin.ignore();
cout << "Incorrect entry. Try again: ";
}