为什么这段代码最终会进入一个无限循环,读取std::cin

Why does this code end up in an infinite loop, reading from std::cin

本文关键字:无限循环 一个 读取 cin std 段代码 代码 为什么      更新时间:2023-10-16

Hi我试图通过向量为我的函数创建一个输入函数。

然而,我不知道为什么我的输入变成了无限循环?

do {            
cout << "Please enter the next number: ";
cin >> num;
number.push_back(num);
cout << "Do you want to end? enter 0 to continue.";
dec = NULL;
cin >> dec;
} while(dec == 0);

"我不知道为什么我的输入变成了无限循环。">

我能想象的唯一原因是,任何不正确的输入都会将cin设置为fail状态。在这种情况下(例如,输入了一个无效的数字,或者只按下了ENTER),cin被设置为fail状态,并且您在dec中的值不会再更改。一旦cin处于fail状态,任何后续的输入操作都将分别失败,并且输入的主题不会改变。

为了防止这种行为,您必须先clear()std::istream的状态,并读取到安全点,然后再继续(另请参阅:如何测试字符串流运算符>>是否解析了错误类型并跳过它):

do {
cout << "Please enter the next number: ";
if(cin >> num) {
number.push_back(num);
}
else {
cerr << "Invalid input, enter a number please." << std::endl;
std::string dummy;  
cin.clear();
cin >> dummy;
}
cout << "Do you want to end? enter 0 to continue.";
dec = -1;
if(!(cin >> dec)) {
std::string dummy;  
cin.clear();
cin >> dummy;
break; // Escape from the loop if anything other than 0 was
// typed in
}
} while(dec == 0);

以下是三个使用不同输入来结束循环的工作演示:

第一次输入:

1
0
2
0
3
0
4

输入

第二个输入:

1
0
2
0
3
0
4
xyz

第三输入

1
0
2
0
3
0
4
42

循环是有限的,以上所有的输出都是

1234

您还应该注意,我已经将bool dec;更改为int dec;,但这可能只是一个小问题