从文本文件到二维整型数组C时的读数矩阵++ [英] Reading matrix from a text file to 2D integer array C++

查看:193
本文介绍了从文本文件到二维整型数组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

我有一个.txt文件这样的矩阵。现在,我怎么读最好的办法这个数据到 INT ** 输入二维数组的?我找遍所有网站上也没有找到一个满意的答案。

  array_2d =新为int * [5];
        的for(int i = 0;我小于5;我++)
            array_2d [I] =新INT [7];        ifstream的file_h(FILE_NAME_H);        //什么在这里做?        file_h.close();


解决方案

首先,我想你应该创建大小7和循环的为int * [] 从1到7,而你初始化的5环内的i​​nt数组。

在这种情况下,你可以这样做:

  array_2d =新为int * [7];ifstream的文件(FILE_NAME_H);为(unsigned int类型I = 0;我7;;我++){
    array_2d [I] =新INT [5];    为(unsigned int类型J = 0; J< 5; J ++){
        文件>> array_2d [I] [J]。
    }
}

编辑(一个相当长的时间后):结果,
另外,我建议使用矢量阵列

 的std ::阵列<的std ::阵列< INT,5>中7个数据;
性病:: ifstream的文件(FILE_NAME_H);对(INT I = 0; I&7; ++ⅰ){
    为(中间体J = 0; J&小于5 ++ j)条{
        文件>>数据[I] [J]。
    }
}

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

解决方案

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];
    }
}

这篇关于从文本文件到二维整型数组C时的读数矩阵++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆