【问题标题】:Not waiting for std::cin.ignore()不等待 std::cin.ignore()
【发布时间】:2018-07-15 21:14:51
【问题描述】:

基于this answer,我编写了如下代码

#include <iostream>
#include <vector>
#include <cstddef>
#include <limits>

int main()
{
    std::cout << "Enter x and y size, followed by enter: ";
    std::size_t nrOfRows, nrOfCols;
    std::cin >> nrOfRows >> nrOfCols;

    // initialize dynamic array of arrays
    std::vector<std::vector<char>> data(nrOfRows,
        std::vector<char>(nrOfCols, 'O'));

    // print array
    for (std::size_t rowNr = 0; rowNr < nrOfRows; rowNr++)
    {
        std::cout << "Row " << rowNr << ": ";
        for (const auto& el : data[rowNr])
            std::cout << el << " ";
        std::cout << std::endl;
    }
    std::cout << "Press enter to continue: ";
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

使用 VC++ 14.1 或 Visual Studio 2017 v15.7.4 编译。 在第一个提示之后,我输入例如“3 5”并输入。然后程序只是滚动并退出。例如。它输出字符串并且不等待std::cin.ignore() 处的最终用户输入(回车)。

我错过了什么?

编辑

对于反对者/反对者。此代码确实按描述工作。

#include <iostream>
#include <limits>

int main()
{
    std::cout << "Press enter to continue: ";
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

【问题讨论】:

  • @RetiredNinja 据我所知ignore() 确实暂停了程序。问题是提取运算符留下的换行符。
  • 猜你是对的,如果缓冲区中没有任何内容,它会阻塞。每天学习新东西。

标签: c++ iostream


【解决方案1】:

您的问题是提取操作 (std::cin &gt;&gt; nrOfRows &gt;&gt; nrOfCols;) 将在流中留下定界空格,这与 getline() 不同,后者会消耗定界符。这通常不是问题,因为&gt;&gt; 运算符也会忽略前导空格,但流中留下的换行符会导致std::istream::ignore() 不等待输入。

要解决此问题,请在输出 Press enter to continue: 消息之前添加对 std::istream::ignore() 的调用以丢弃所有空格。

【讨论】:

    猜你喜欢
    • 2017-05-03
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    相关资源
    最近更新 更多