用户输入整数 - 错误处理 [英] User Input of Integers - Error Handling
问题描述
我对我的程序的某些输入区域有些麻烦。有几个部分,用户输入特定的整数。即使他们输入错误的,这是所有罚款和dandy,但我注意到,如果他们输入任何非整数类型,如'm',那么它会循环错误消息重复。
我有一些功能,它们有整数输入。下面是一个例子。
void Room :: move(vector< Room>& v,int exone,int extwo, int exthree,int current)
{
v [current] .is_occupied = false;
int room_choice;
cout<< \\\
输入房间移动到:;
while(true)
{
cin>>房间
if(room_choice == exone || room_choice == extwo || room_choice == exthree)
{
v [room_choice] .is_occupied = true;
break;
}
else cout<< 输入不正确,请重试:;
}
}
[已解决]
void Room :: move(vector< Room>& v,int exone,int extwo,int exthree,int current)
{
v [current] .is_occupied = false;
int room_choice;
cout<< \\\
输入房间移动到:;
while(true)
{
cin>>房间
if(room_choice == exone || room_choice == epwo || room_choice == exthree)
{
v [room_choice] .is_occupied = true;
break;
}
else if(cin.fail())
{
cin.clear()
cin.ignore()
cout< 输入不正确,请重试:;
}
}
}
您可以使用 cin.good()
或 cin.fail()
处理提供的输入值。然后,如有必要,您可以使用 cin.clear()
清除错误状态,然后再继续处理。
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: ";
}
}
[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: ";
}
}
}
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.
这篇关于用户输入整数 - 错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!