为什么这段代码最终会进入一个无限循环,读取std::cin
Why does this code end up in an infinite loop, reading from std::cin
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;
,但这可能只是一个小问题
相关文章:
- Qt 在另一个线程中无限循环
- 为什么这个递归函数会创建一个无限循环?
- 如何找出为什么我的程序一直有一个无限循环?
- 只有一个正确解决方案的无限循环
- 为什么我有一个无限循环,我如何以不同的方式做到这一点
- WinUsb_WritePipe进入了一个无限循环
- 为什么我会得到一个无限循环(因子)?
- 为什么我总是得到一个无限循环
- 在无限循环C 内定义一个变量
- 这是一个无限循环吗?程序提前完成
- 为什么它是一个无限循环?
- 为什么我的程序在输入字符时有一个无限循环
- C++使用在另一个结构中定义的结构导致无限循环
- 为什么这段代码最终会进入一个无限循环,读取std::cin
- 为什么一个空的无限循环会占用我的整个CPU
- 如何使其成为一个无限循环
- 如何安全地关闭一个有无限循环的THREAD
- Tcl_CreateInterp怎么会变成一个无限循环呢
- C++,得到一个无限循环
- 而(file_object)是一个导致无限循环