tri*_*ker 6 c++ error-handling
我在程序的某些输入区域遇到了一些麻烦.用户输入特定整数的部分内容.即使他们输入了一个非常精细和花花公子的错误,但我注意到如果他们输入的内容不是像'm'这样的整数类型,那么它将重复循环错误消息.
我有几个函数,其中包含整数输入.这是一个例子.
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: ";
}
}
Run Code Online (Sandbox Code Playgroud)
[解决了]
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: ";
}
}
Run Code Online (Sandbox Code Playgroud)
APr*_*mer 11
您的"已解决"代码中仍然存在问题.您应该在检查值之前检查fail().(显然,与格式问题相反,存在eof()和IO故障的问题).
习惯性的阅读是
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
}
Run Code Online (Sandbox Code Playgroud)