c++ - 为什么我按一个字母时会出现无限循环?如何更改以进行错误检查?

标签 c++ error-handling error-checking

为什么我在按字母时会出现无限循环?如何防止我的代码在错误检查时进入无限循环?

#include <iostream>
using namespace std;

int main()
{
    int number;
    cout << "Enter a number in the range 1-100: ";
    cin >> number;

    while (number > 1 || number < 100)
    {
        cout << "ERROR: Enter a value in the range 1-100: ";
        cin >> number;

    }
    return 0;
}

最佳答案

因为 std::cin 是类型安全的,它知道字母不是“int number”的有效输入。它在 std::cin 中引发错误标志,任何后续操作都将失败并立即返回。

在继续之前,您需要检查错误状态并清除所有错误标志。

查看现有帖子 Why do I get an infinite loop if I enter a letter rather than a number?

关于c++ - 为什么我按一个字母时会出现无限循环?如何更改以进行错误检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39800593/

相关文章:

php - 既然所有错误都是异常,PHP7 上的 set_error_handler() 会发生什么?

java - 导致创建注释的多个实例的逻辑问题

Java 验证日期条目

c++ - 为什么由于标量删除而调用 vector 删除析构函数?

python-3.x - 如果文件用 int 而不是 string 写入,python 中的错误处理

python - 类型错误:* 不支持的操作数类型: 'function' 和 'int' BMI 计算器

C. 检查特定小数位数的 float 输入

c++ - 为什么 std::bind 在这个例子(成员函数)中没有占位符就不能工作?

c++ - C++ 中的关联键到键映射

c++ - 每次构建(制作)lib,仅当 lib 较新时才重新编译项目