您好,我尝试通过 vector 为我的函数创建一个输入函数。
但是,我不知道为什么我的输入会变成死循环?
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);
最佳答案
"I don't know why my input become infinite loop."
我能想到的唯一原因是,任何不正确的输入集 cin
至 fail
状态。在这种情况下(例如,输入了无效数字,或者只是按下了 ENTER)cin
设置为 fail
在 dec
中陈述和你的值(value)永远不会改变。一次cin
在fail
state 任何后续的输入操作都将分别失败,并且输入的主题不会改变。
为了防止这种行为,你必须clear()
std::istream
的状态,并在继续之前阅读到安全点(另请参阅:How to test whether stringstream operator>> has parsed a bad type and skip it):
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;
,但这可能是次要的一点。
关于c++ - 为什么这段代码以无限循环结束,从 std::cin 读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29633122/