while 循环对非整数的响应很奇怪
While loop responds strangely to non integer
所以我在运行它时遇到了问题,我正在测试以确保 while 循环正常工作。如果为 cin <<a 输入非整数值;循环将无休止地执行,而不会要求进一步的 a 值,如果输入的是整数但不是列出的一个,它工作正常,但我希望它考虑到用户尝试的任何输入。有没有简单的方法来解决这个问题?我认为它与 int 有关,但我稍后需要一个 int 作为 switch 语句。
int a;
cout << "What type of game do you wish to play?n(Enter the number of the menu option for)n(1):PVPn(2):PvEn(3):EVEn";
cin >> a;
while (!((a == 1) || (a == 2) || (a == 3)))
{
cout << "That is not a valid gametype. Pick from the following menu:n(1):PVPn(2):PvEn(3):EVEn";
a = 0;
cin >> a;
}
cin >> a;
如果此代码失败(如果提供非整数数据,则失败(,流将进入无效状态,并且所有后续对cin >> a
的调用将立即返回,没有副作用,仍处于错误状态。
这是我不是特别喜欢的一个C++设计决策(可能是为什么大多数人不喜欢 C++ 年的 Streams 设计(,因为你会期望这会引发错误或之后恢复正常,就像大多数其他语言一样。相反,它会静默失败,这是许多程序错误的最大来源。
无论如何,有两种可能的解决方法。
首先是正确检查流是否仍然有效。这样:
while (!((a == 1) || (a == 2) || (a == 3)))
{
cout << "That is not a valid gametype. Pick from the following menu:n(1):PVPn(2):PvEn(3):EVEn";
a = 0;
if(!(cin >> a)) break; //Input was invalid; breaking out of the loop.
}
如果输入无效,这将中断循环,但使流处于无效状态。
另一个解决方法是将流重置为有效状态。
while (!((a == 1) || (a == 2) || (a == 3)))
{
cout << "That is not a valid gametype. Pick from the following menu:n(1):PVPn(2):PvEn(3):EVEn";
a = 0;
while(!(cin >> a)) {
std::cin.clear();
std::cin.ignore(numeric_limits<streamsize>::max(), 'n');
std::cout << "Please only enter Integers." << std::endl;
}
}
第二种通常是人们需要的方法,但在某些情况下,第一种方法可能更有意义。
我让它工作:
int a;
cout << "What type of game do you wish to play?n(Enter the number of the menu option for)n(1):Player V Playern(2):Player vCompn(3):Comp V Compn";
cin >> a;
while (a != 1 && a != 2 && a != 3 || cin.fail())
{
cout << "That is not a valid gametype. Pick from the following menu:n(1):Player V Playern(2):Player vCompn(3):Comp V Compn";
cin.clear();
cin.ignore(256, 'n');
cin >> a;
}
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 在C++中手动调整数组大小
- 检查输入是否不是整数或数字
- C++使用整数的压缩数组初始化对象
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 如何只允许用户输入正整数
- 如何在c++中从文本文件中逐行读取整数
- C++:如何循环通过向量中的整数元素
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 序列化,没有库的整数,得到奇怪的结果
- 在一定长度后从数组中打印时缺少整数
- std::当在256字节边界上写入整数时,流的奇怪行为
- 内联程序集printf将整数解释为地址
- 是否基于数组B整数打印数组A中的整数
- while 循环对非整数的响应很奇怪