异常基础知识:为什么 while 循环会变成无限循环?

Exception basics: why is the while loop turning into an infinite loop?

本文关键字:无限循环 循环 基础知识 为什么 while 异常      更新时间:2023-10-16

这是我的代码:

#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 的语句外没有停止。