Skip to content

Instantly share code, notes, and snippets.

@pileon
Created December 7, 2017 13:53
Show Gist options
  • Save pileon/3d013129634c5b5ff3fc77728bc50f31 to your computer and use it in GitHub Desktop.
Save pileon/3d013129634c5b5ff3fc77728bc50f31 to your computer and use it in GitHub Desktop.
Read X number of lines with an indeterminate number of integers
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>
int main()
{
size_t number_of_rows;
std::cout << "Enter the number of rows: ";
std::cin >> number_of_rows;
// Create vectors of vectors
std::vector<std::vector<int>> rows_of_numbers(number_of_rows);
// Skip the newline from the previous input
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// Now read each line
for (auto &row : rows_of_numbers)
{
// Read the line
std::string line;
std::getline(std::cin, line);
// Parse each line into a sequence of numbers
std::istringstream iss(line);
row = std::vector<int>(std::istream_iterator<int>(iss), std::istream_iterator<int>());
}
// Display each row
for (auto const &row : rows_of_numbers)
{
for (auto const value : row)
{
std::cout << value << ' ';
}
std::cout << '\n';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment