Answer the question
In order to leave comments, you need to log in
How to optimally read matrix from c++ console?
It is required to read the matrix from the console, the input is:
2 2
1 3
4 5
int main() {
int n, k;
char *str;
vector < vector<int> > g;
cin >> k >> n;
for (int i = 0; i < k; i++) {
cin.getline(str, n * 2 - 1);
for (int j = 0; j < n * 2 - 1; j=j*2){
g[i].push_back(atoi(reinterpret_cast<const char *>(str[j])));
}
}
}
Answer the question
In order to leave comments, you need to log in
you are most likely not using the cin.getline method correctly
here is the first link on this question
And you are also accessing a non-writable memory area:
g[i].push_back(...
To solve the second problem, you can pre-allocate memory for the vector using the reserve() method
or rewrite part of the code as then like this:
vector<int> v;
for (int j = 0; j < n * 2 - 1; j=j*2){
v.push_back(atoi(reinterpret_cast<const char *>(str[j])));
}
g.push_back(v);
getline you need to pass a pointer to an already allocated memory block,
you can use std::getline(istr, string) instead of istream::getline
Well, further down the code it’s even worse
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question