c++ - 为什么不 std :cin recognise enter key

标签 c++ user-input

我正在尝试从命令提示符处获取输入,并将每个由空格或制表符分隔的输入放入 vector ,直到用户按下“输入”。我做不到。这是我的代码

template <typename T> 
vector <T> process_input_stream() {

    T value;
    vector <T> vect;

    string line;
    //read input and populate into vect until return key is pressed
    while (getline(cin, line, '\n')){
        cin >> value;
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
        vect.push_back(value);
    }

    return vect;
}

现在我遇到的问题是,当输入输入时,即使按下回车键,输入屏幕仍然要求更多输入。

最佳答案

line 变量包含整行,换行符除外。

要解析每一行,您可以将 while 循环替换为:

while (getline(cin, line))
{
    istringstream iss(line);
    while (iss >> value)
    {
        vect.push_back(value);
    }
}

关于c++ - 为什么不 std :cin recognise enter key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48306210/

相关文章:

python - 如何将 url 作为用户输入传递以通过 Selenium 和 Python 进行调用?

java - Java 中的菜单字符

java - 尝试使用用户输入创建矩阵时出现编译错误。 java

c++ - 优化 Stack-Walking 性能

python - 使用批处理文件在 python 中获取用户输入

c++ - 对同一类的多个不同对象使用 1 个唯一的 MFC 对话框

c++ - 如果 "std::cin"的输入不正确那么它会崩溃但程序的其余部分会工作

java - 查找数组中数字的位置并给出点,Java

c++ wait_until奇怪的超时行为

c++ - code::Block 中的 OTL 4.0