L
L
lleviy2020-02-19 23:37:37
C++ / C#
lleviy, 2020-02-19 23:37:37

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

, where the first row is the number of rows and columns, all subsequent ones are the matrix itself.

I tried to do so. A segmentation error still occurs on the line with getline (I suspect that an error will also occur further when trying to push to g[i]).
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])));
        }
    }
}


Maybe there is an easier way to do this? And can you explain why getline gives a segmentation error, everything seems to be fine with the code up to this point.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
TriKrista, 2020-02-20
@lleviy

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);

V
Vasily Melnikov, 2020-02-20
@BacCM

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 question

Ask a Question

731 491 924 answers to any question