我是 C++ 的新手,我使用的是 Visual Studio 2015。
cin
在 "Please enter another integer:\n"
之后不等待输入,每次都输出 "You entered 0"
。
我在互联网上搜索了一个多小时没有解决方案。 cin.ignore()
的组合均无效。为什么 cin
缓冲区仍未清除?
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vals;
int val = 0;
int n = 0;
cout << "Please enter some integers (press a non-numerical key to stop)\n";
while (cin >> val)
vals.push_back(val);
cin.ignore(INT_MAX, '\n');
cin.ignore();
cout << "Please enter another integer:\n";
cin.ignore();
cin >> n;
cout << "You entered " << n;
system("pause");
return 0;
}
最佳答案
问题是用户退出循环需要将 cin 置于失败状态。这就是为什么你的
while(cin >> val){ .... }
正在工作。
如果处于失败状态,cin 不再能够为您提供输入,那么您需要 clear()失败的状态。您还需要忽略()最初触发失败状态的先前非整数响应。
用起来也有好处
if(cin >> n){
cout << "You entered " << n;
}
这将断言为 n
提供了正确的输入。
关于c++ - 尽管有 cin.ignore(),但 Cin 没有等待输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41212202/