User Input Is Never Easy
There is a lot that may go wrong, and you must always handle it carefully.
The end goal, then, should be to make input reasonable for the end user, and not necessarily “pretty”.
For example:
#include <algorithm>
#include <cctype>
#include <iostream>
#include <iterator>
#include <vector>
#include <sstream>
#include <string>
struct matrix: public std::vector<std::vector<int>> { };
std::istream& operator >> (std::istream& ins, matrix& m)
{
std::string s;
std::size_t cols = 0;
// while input and not a blank line
while (std::getline(ins, s) and !s.empty())
{
// scan one row from the input line
std::istringstream ss{ s };
std::vector<int> row;
std::copy(std::istream_iterator<int>(ss), std::istream_iterator<int>(), std::back_inserter(row));
// make sure that the source input stream fails if the intermediary fails
if (ss.fail())
{
ins.setstate(std::ios::failbit);
return ins;
}
m.emplace_back(row);
// keep track of maximum number of columns
cols = std::max(cols,row.size());
}
// make sure the matrix has the same number of columns in each row
for (auto& row : m) row.resize(cols);
return ins;
}
int main()
{
matrix m;
std::cout << "Enter the matrix, one row per line.\n"
"Press Enter twice when done:\n";
std::cin >> m;
auto rows = m.size();
auto cols = m.size() ? m[0].size() : 0;
std::cout << "Your matrix has " << rows << " rows and " << cols << " columns.\n";
}
Clearly, this is far from pretty. But it does the Right Thing.
Hope this helps.