从文本文件读取矩阵到二维整数数组 C++ [英] Reading matrix from a text file to 2D integer array C++
本文介绍了从文本文件读取矩阵到二维整数数组 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**
类型的二维数组?我搜索了整个网络,但没有找到满意的答案.
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();
推荐答案
首先,我认为你应该创建一个大小为 7 的 int*[]
并在你在循环内初始化一个 5 的 int 数组.
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];
}
}
编辑(经过相当长的时间后):
或者,我建议使用 vector
或 array
:
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屋!
查看全文