简体   繁体   English

读取矩阵从文本文件到2D整数数组C ++

[英]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. 我在.txt文件中有这样的矩阵。 Now, how do I read this data into a int** type of 2D array in best way? 现在,如何以最佳方式将此数据读入int**类型的2D数组? 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();

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. 首先,我认为你应该创建一个大小为7的int*[]并在循环中初始化一个5的int数组时从1循环到7。

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 : 或者,我建议使用vectorarray

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];
    }
}
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. 我希望它有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM