c++ - While 循环对非整数的响应很奇怪

标签 c++ while-loop

因此,在我测试以确保 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):PVP\n(2):PvE\n(3):EVE\n";
cin >> a;
while (!((a == 1) || (a == 2) || (a == 3)))
{
    cout << "That is not a valid gametype. Pick from the following menu:\n(1):PVP\n(2):PvE\n(3):EVE\n";
    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):PVP\n(2):PvE\n(3):EVE\n";
    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):PVP\n(2):PvE\n(3):EVE\n";
    a = 0;
    while(!(cin >> a)) {
        std::cin.clear();
        std::cin.ignore(numeric_limits<streamsize>::max(), '\n');
        std::cout << "Please only enter Integers." << std::endl;
    }
}

第二种通常是人们需要的方法,但在某些情况下第一种可能更有意义。

关于c++ - While 循环对非整数的响应很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45337331/

相关文章:

java - 使用随机 int 的 ArrayIndexOutOfBoundsException

c++ - 将 QString 转换为 char* 不稳定?

c++ - 128 位 int 是用 C/C++ 中的两条指令编写还是加载?

c++ - 直接跳转到另一个C++函数

python - 如何将整数转换为以 256 为基数的表示形式?

bash 脚本 : commands after the loop are not executed if the loop condition is false

Java – 重复用户输入的方法

c++ - 如何将 iostream 从二进制模式切换到文本模式,反之亦然?

c++ - VS2010 中的名称查找错误

java - 如何从一个线程中打破另一个线程中的循环?