c++ - 异常基础 : why is the while loop turning into an infinite loop?

标签 c++ loops while-loop

<分区>

这是我的代码:

#include <iostream>
int main(){
    int x;
    int y = 1;
    while(x != y){
        std::cout << "Please, enter 1." << std::endl;
        std::cin >> x;
        try{
            if(x != y){
            throw 2;
           }
        }
        catch(int){
            std::cout << "You didn't enter 1." << std::endl;
        }
    }
    if(x == 1){
        std::cout << "Well done." << std::endl;
    }
    return 0;
}

当我提供 1 作为输入时,它运行良好,按预期输出消息“Well done”。但是,当我向 cin 提供任何其他类型的输入时,代码会生成一个循环,无限期地打印出消息“您没有输入 1”。我想知道为什么会这样。

最佳答案

在你给x的非整数值之后,

cin >> x

cin 进入错误状态,无法进一步读取。所以循环继续,因为除了包含 cin 的语句外没有停止。

关于c++ - 异常基础 : why is the while loop turning into an infinite loop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50479847/

相关文章:

PHP如何循环遍历多个注释级别

python 3 : How to best iterate over all lines in a big file (+1 million lines) in a random order

bash 同时 [: too many arguments

php - 循环嵌套,我得到一个空白页 (php)

c++ - 通过ODBC创建数据库

循环中的java变量不计数

c++ - InternetReadFile() 似乎没有读取互联网数据

c - float变量不满足条件(C)

c++ - DirectX 9 顶点球体

c++ - 我可以防止使用重载运算符 == 与 NULL 进行比较吗?