异常基础知识:为什么 while 循环会变成无限循环?
Exception basics: why is the while loop turning into an infinite 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 作为输入时,它工作得很好,按预期输出消息"干得好"。但是,当我向cin提供任何其他类型的输入时,代码会生成一个循环,无限期地打印出消息"您没有输入 1"。我想知道为什么会这样。
在你给出非整数值 x 之后,
cin >> x
CIN 进入错误状态,无法进一步读取.. 所以循环继续,因为除了包含 CIN 的语句外没有停止。
相关文章:
- 有没有办法重复循环循环?
- 无限而循环不工作C++
- 我在C 初学者中发现了无限的循环问题
- 谁能告诉我为什么我的程序在无限的循环中进行
- 虽然第三次循环循环,尽管在我眼中没有满足它的条件,因此打印了一个空字符串
- 避免以不同的迭代剂的循环循环避免几乎相同的代码重复
- 为什么这条线是无限的循环
- 我得到一个无限的循环,我不确定为什么或如何修复它
- C 更改了与循环无关的东西后,卡在无限的循环中
- 为什么我有这个无限的循环
- 试图打破一段循环时,卡在无限的循环中
- 如何通过在Qt中按esc来摆脱无限while循环
- 我的声明是无限的循环
- 无限 while 循环 - 字符关闭不起作用C++
- 无限 while 循环在要求用户输入 2 个数字时发生
- 在无限 while 循环中调用 Sleep() 有多重要
- C++:布尔表达式导致无限 while 循环
- 读取所有数据后进行无限cin循环
- 如何修复一个无限while循环
- C字符串无限For循环的小C[]