4
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();
0

2 Answers 2

7

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];
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much. " file >> array_2d[i][j]; " This line was all I have been asking for.
@burakongun To add to Magtheridon's comment that the array should be structured (7 x 5) is because the is ordering of the array in the file is by line number and then by integer on each line (this logically matches the order in which the file is read in). If you use your original structure and loop from i=(0 to 4) and j=(0 to 6) with "file >> array2d[i][j]", you will not get a correct representation of your original array. You will instead get {{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}} which is not a valid representation of the 2D array in your question.
3
for (int i = 0; i < n; i++) {
 for (int j = 0; j < n; j++) {
    int n;
    fscanf(pFile, "%d", &n);
    printf("(%d,%d) = %d\n", i, j, n);
    array[i][j] = n;
}

I hope it helped.

3 Comments

-1 for: completelly weird google link, this should be a comment and answers themselves should contain useful advice.
These are too complex for what I actually need. But thanks anyway.
And sorry for my late reply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.