User Input of Integers - Error Handling(整数的用户输入 - 错误处理)
问题描述
我的程序的某些输入区域有问题.用户输入特定整数的部分有几个部分.即使他们输入了错误的,也很好,但我注意到如果他们输入了任何非整数类型的东西,比如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.
这篇关于整数的用户输入 - 错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:整数的用户输入 - 错误处理
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
