尽管有 cin.ignore(),但 Cin 没有等待输入

Cin not waiting for input despite cin.ignore()

我是 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;
}

您的程序中的问题是它需要整数,而用户可以输入任何内容,例如非整数字符。

一个更好的方法来做你似乎想做的事情是逐个读取字符,忽略空格,如果是数字,则继续读取以获得整数,否则停止循环。然后你可以读取所有字符,直到到达'\n',并对一个数字执行相同的操作。在执行此操作时,对于每个字符,您应该使用 cin.eof().

检查流中是否仍然存在字符

此外,您可以通过在终止应用程序之前请求最后一个字符来防止命令行 window 关闭,而不是使用系统 ("pause")。

问题是用户退出循环需要将 cin 置于失败状态。这就是为什么你的

while(cin >> val){ .... }

正在工作。

如果处于失败状态,cin 不再能够为您提供输入,因此您需要 clear() 失败状态。您还需要忽略()最初触发失败状态的先前非整数响应。

使用

也有好处
if(cin >> n){
    cout << "You entered " << n;
}

这将断言已为 n 提供了正确的输入。

尝试像这样获取整数:

#include <sstream>

...
fflush(stdin);
int myNum;
string userInput = "";

getline(cin, userInput);
stringstream s (userInput);
if (s >> myNum) // try to convert the input to int (if there is any int)
    vals.push_back(myNum);

如果没有 sstream,你必须使用 try catch,这样当输入不是整数时你的程序就不会崩溃