Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading matrix from a text file to 2D integer array C++

1 3 0 2 4 
0 4 1 3 2 
3 1 4 2 0 
1 4 3 0 2 
3 0 2 4 1 
3 2 4 0 1 
0 2 4 1 3

I have a matrix like this in a .txt file. Now, how do I read this data into a int** type of 2D array in best way? I searched all over the web but could not find a satisfying answer.

array_2d = new int*[5];
        for(int i = 0; i < 5; i++)
            array_2d[i] = new int[7];

        ifstream file_h(FILE_NAME_H);

        //what do do here?

        file_h.close();
like image 263
burakongun Avatar asked Dec 27 '22 07:12

burakongun


1 Answers

First of all, I think you should be creating an int*[] of size 7 and looping from 1 to 7 while you initialize an int array of 5 inside the loop.

In that case, you would do this:

array_2d = new int*[7];

ifstream file(FILE_NAME_H);

for (unsigned int i = 0; i < 7; i++) {
    array_2d[i] = new int[5];

    for (unsigned int j = 0; j < 5; j++) {
        file >> array_2d[i][j];
    }
}

EDIT (After a considerable amount of time):
Alternatively, I recommend using a vector or an array:

std::array<std::array<int, 5>, 7> data;
std::ifstream file(FILE_NAME_H);

for (int i = 0; i < 7; ++i) {
    for (int j = 0; j < 5; ++j) {
        file >> data[i][j];
    }
}
like image 104
user123 Avatar answered Dec 29 '22 10:12

user123