[英]C++ reading in a matrix-style text file into a 2D array, keeping only numerical blocks
[英]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
我在.txt文件中有這樣的矩陣。 現在,如何以最佳方式將此數據讀入int**
類型的2D數組? 我在網上搜索但找不到令人滿意的答案。
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數組時從1循環到7。
在這種情況下,你會這樣做:
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
:
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;
}
我希望它有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.