【发布时间】:2021-04-21 20:37:15
【问题描述】:
我有一个包含值的文本文件,我想将它们放入二维向量中。
我可以用数组做到这一点,但我不知道如何用向量做到这一点。
向量大小应该像我事先不知道的vector2D[nColumns][nLines]。我最多可以在文本文件中有列数,但不能有行数。 列数可能不同,从一个 .txt 文件到另一个。
.txt 示例:
189.53 -1.6700 58.550 33.780 58.867
190.13 -3.4700 56.970 42.190 75.546
190.73 -1.3000 62.360 34.640 56.456
191.33 -1.7600 54.770 35.250 65.470
191.93 -8.7500 58.410 33.900 63.505
使用数组我这样做:
//------ Declares Array for values ------//
const int nCol = countCols; // read from file
float values[nCol][nLin];
// Fill Array with '-1'
for (int c = 0; c < nCol; c++) {
for (int l = 0; l < nLin; l++) {
values[c][l] = -1;
}
}
// reads file to end of *file*, not line
while (!inFile.eof()) {
for (int y = 0; y < nLin; y++) {
for (int i = 0; i < nCol; i++) {
inFile >> values[i][y];
}
i = 0;
}
}
【问题讨论】:
-
while (!inFile.eof())是错误的。别这样! -
@LightnessRacesinOrbit 应该改用什么?