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.
这篇关于整数的用户输入 - 错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:整数的用户输入 - 错误处理
- STL 中有 dereference_iterator 吗? 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 静态初始化顺序失败 2022-01-01
- 近似搜索的工作原理 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- C++ 协变模板 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
