while 循环对非整数的响应很奇怪

While loop responds strangely to non integer

本文关键字:响应 整数 循环 while      更新时间:2023-10-16

所以我在运行它时遇到了问题,我正在测试以确保 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;
}