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

标签 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;
}

最佳答案

问题是用户退出循环需要将 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/

相关文章:

c++ - 在 C++ 中,将正数转换为 1 并将负数转换为 0 的最快方法

C - 查找句子中最长的单词

C 缓冲区下溢定义和相关风险

android - 如何使用 Android NDK 将整数颜色的像素数组绑定(bind)到纹理?

c++ - 如何查找只包含某个字段而没有其他字段的列表?

c++ - C++ 结构体中的指针

c++ - 将整数存储为 float

c# - 如何使用表单提交的绑定(bind)值为 InputText 设置占位符?

python - 如何在 Python 3 中使用 input() 读取文件

vim - vim 中的缓冲区和寄存器有什么区别?