开发者

Reading 2D/Multidimensional Array From a .txt File In C++

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    const int m = 5, n = 2;

    int arr[m][n]{};

    ifstream iFile;
    iFile.open("TextFile1.txt");

    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            iFile >> arr[i][j];
        }
    }

    iFile.close();

    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            cout << arr[i开发者_运维百科][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

The code above was written to read a .txt file containing numbers [1-10] in a 5 by 2 array.

My issue is when the code is complied I get my desired 5 x 2 grid though it seems the file isn't being read resulting to this:

0 0
0 0
0 0
0 0
0 0

When I should really be getting this as an output:

1 2
3 4 
5 6
7 8
9 10

I also would like to know how I can build off of this to read 3 x 3 arrays for example.

Thank you! :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜