【问题标题】:Cin not waiting for input despite cin.ignore()尽管 cin.ignore(),Cin 不等待输入
【发布时间】:2017-05-03 21:23:58
【问题描述】:

我是 C++ 新手,我正在使用 Visual Studio 2015。

cin"Please enter another integer:\n" 之后不等待输入,每次都输出"You entered 0"

我已经在 Internet 上搜索了一个多小时,但没有找到解决方案。 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;
}

【问题讨论】:

标签: c++ input buffer iostream cin


【解决方案1】:

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

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

正在工作。

如果 cin 处于失败状态,无法再为您提供输入,那么您需要 clear() 失败状态。您还需要 ignore() 最初触发失败状态的先前非整数响应。

用起来也有好处

if(cin >> n){
    cout << "You entered " << n;
}

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

【讨论】:

  • cin.clear(); 后跟 cin.ignore(INT_MAX, '\n'); 有效
  • @user6616363 std::numeric_limits&lt;std::streamsize&gt;::max() 作为忽略的第一个参数是首选。
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

    尝试像这样获取整数:

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

    【讨论】:

    • 输入流在失败时不会抛出异常。
    • sstream 如果一切正常则返回 true,如果有错误则返回 false
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 2018-06-01
    • 2023-03-10
    • 2012-01-24
    • 2012-08-29
    • 1970-01-01
    相关资源
    最近更新 更多