【问题标题】:why does not std:cin recognise enter key为什么 std:cin 不能识别回车键
【发布时间】:2018-01-17 16:53:37
【问题描述】:

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

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

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

【问题讨论】:

  • 你认为while(getline(...)) 是做什么的?
  • (并且您忽略了实际提取的line)。所以你需要一个if(不是真的,失败后line会是空的)和一个std::istringstream

标签: c++ user-input


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 2011-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多