从文本文件读取矩阵到二维整数数组 C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15588800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading matrix from a text file to 2D integer array C++
提问by burakongun
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.
我在 .txt 文件中有一个这样的矩阵。现在,我如何int**
以最佳方式将这些数据读入一种二维数组?我搜索了整个网络,但找不到满意的答案。
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();
回答by Mohamad Ali Baydoun
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.
首先,我认为您应该创建一个int*[]
大小为 7 并从 1 到 7 的循环,同时在循环内初始化一个 5 的 int 数组。
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
:
编辑(经过相当长的时间后):
或者,我建议使用 avector
或 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];
}
}
回答by George Netu
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.
我希望它有所帮助。