3

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');
}
Community
  • 1
  • 1
JHBonarius
  • 10,824
  • 3
  • 22
  • 41
  • 2
    @RetiredNinja As far as I know `ignore()` does pause the program. The problem is the line break left in there by the extraction operator. – eesiraed Jul 15 '18 at 21:31
  • Guess you're right, if there's nothing in the buffer it blocks. Learn something new every day. – Retired Ninja Jul 15 '18 at 21:46

1 Answers1

4

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.

eesiraed
  • 4,626
  • 4
  • 16
  • 34