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');
}
2
  • 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
    Commented Jul 15, 2018 at 21:31
  • Guess you're right, if there's nothing in the buffer it blocks. Learn something new every day. Commented Jul 15, 2018 at 21:46

1 Answer 1

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.