【发布时间】: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 -g和GCC。然后use thegdbdebugger了解你程序的行为 -
x在初始化之前使用。行为未定义。 -
永远不要抛出任何不是来自
std::exception的东西。
标签: c++ loops while-loop