尽管cin.ignore(),Cin不等待输入

时间:2016-12-18 19:47:45

标签: c++ input buffer iostream cin

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

3 个答案:

答案 0 :(得分:2)

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

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

正在运作。

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

使用

也是有用的
if(cin >> n){
    cout << "You entered " << n;
}

这将声明提供了n的正确输入。

答案 1 :(得分:0)

你的程序中的问题是它需要整数,而用户可以输入任何东西,比如非整数字符。

做一个你想要做的事情的更好的方法是逐个读取字符,忽略空格,如果它是一个数字,那么继续阅读以得到整数,否则停止循环。然后,您可以阅读所有字符,直到达到&#39; \ n&#39;,并为一个数字执行相同操作。当您这样做时,对于每个字符,您应该使用cin.eof()检查流中是否仍有字符。

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

答案 2 :(得分:-1)

尝试获得这样的整数:

#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,所以当输入不是整数时你的程序不会崩溃

相关问题