JHBonarius
JHBonarius

Reputation: 11301

Not waiting for std::cin.ignore()

Based on this answer, I've written the following code

#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');
}

Compiled with VC++ 14.1 or Visual studio 2017 v15.7.4. After the first prompt I enter e.g. "3 5" and enter. Then the program just rolls through and exits. E.g. it outputs the strings and does not wait for the final user input (enter) at std::cin.ignore().

What did I miss?

edit

For the down-voters/nay sayers. This code does work as described.

#include <iostream>
#include <limits>

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

Upvotes: 3

Views: 330

Answers (1)

eesiraed
eesiraed

Reputation: 4654

Your problem is that the extraction operation (std::cin >> nrOfRows >> nrOfCols;) will leave delimiting whitespace in the stream, unlike getline(), which will consume the delimiter. This normally isn't a problem because the >> operator will also ignore leading whitespace, but the line break left in the stream will cause std::istream::ignore() to not wait for input.

To fix this, add a call to std::istream::ignore() to discard any whitespace before you output the Press enter to continue: message.

Upvotes: 4

Related Questions