整数的用户输入 - 错误处理
我的程序的某些输入区域有问题.用户输入特定整数的部分有几个部分.即使他们输入了错误的,也很好,但我注意到如果他们输入了任何非整数类型的东西,比如m",那么它会重复循环错误消息.
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 << "
Enter 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: ";
}
}
推荐答案
您可以使用 cin.good()
或 cin.fail()
来判断 cin 是否可以成功处理提供的输入值.如有必要,您可以在继续处理之前使用 cin.clear()
清除错误状态.
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.
相关文章