I need to input elements of vector of vector. Size of vectors is not known.
Row input ends with * character, as well as vector input.
EXAMPLE
2 5 1 3 4 *
9 8 9 *
3 3 2 3 *
4 5 2 1 1 3 2 *
*
Code:
#include <iostream>
#include <vector>
int main() {
std::vector < std::vector < int >> a;
int x;
int i = 0, j = 0;
for (;;) {
while (std::cin >> x) {
a[i][j] = x;
j ;
}
if (!std::cin >> x) break;
i ;
}
return 0;
}
This allows me to enter only the first row, and after that the program stops. Could you help me to modify this to allow input of other rows?
CodePudding user response:
There are two problems with your code:
you are indexing into each
vector
without adding any values to it first, which is undefined behavior.a[i][j] = x;
does not make the vectors grow in size. Usevector::push_back()
instead.You are not handling the input of
*
correctly.x
is anint
, so whenstd::cin >> x
fails to read a non-integer value, like*
,cin
is put into an error state and all further reading fails until youclear()
the error andignore()
the failed data from the input buffer.
Since your input is line-based, consider using std::getline()
to read each line at a time. You can use a std::istringstream
to read integers from each line, eg:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <iomanip>
int main() {
std::vector<std::vector<int>> a;
std::string line;
while (std::getline(std::cin, line)) {
std::istringstream iss(line);
iss >> std::ws;
if (iss.peek() == '*') break;
std::vector<int> v;
int x;
while (iss >> x) {
v.push_back(x);
}
a.push_back(v);
}
return 0;
}