【问题标题】:Exception basics: why is the while loop turning into an infinite loop? [duplicate]异常基础知识:为什么while循环会变成无限循环? [复制]
【发布时间】:2018-11-01 22:33:48
【问题描述】:

这是我的代码:

#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 作为输入时,它工作得很好,按预期输出消息“做得好”。但是,当我向 cin 提供任何其他类型的输入时,代码会生成一个循环,无限期地打印出消息“您没有输入 1”。我想知道为什么会这样。

【问题讨论】:

  • 你给cin的东西看不懂。你认为它去哪儿了?
  • 编译所有警告和调试信息,所以g++ -Wall -Wextra -gGCC。然后use the gdb debugger了解你程序的行为
  • x 在初始化之前使用。行为未定义。
  • 永远不要抛出任何不是来自std::exception的东西。

标签: c++ loops while-loop


【解决方案1】:

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

cin >> x

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

【讨论】:

    猜你喜欢
    • 2017-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    相关资源
    最近更新 更多