[英]Reading txt file into 2d array C++
我知道以前曾有人问过这个问题,但是我似乎找不到我的特定问题的答案。 我正在阅读txt文件。
weather.txt
1 52 32
2 54 32
3 54 30
4 48 28
5 37 25
6 37 25
7 46 34
8 55 45
9 59 46
10 61 37
11 55 32
12 59 34
有更多数据,但是出于空间考虑,我将其放在了这里。
我试图读入数组0,0 1,0 2,0,然后它将变为0.1,1 1,1 2,1,然后是0,2 1,2 2,2。 只是重复行。 有了代码,我现在被卡住了。 输出看起来像这样...
位置:0:0文本文件中的数据:1位置:1:0文本文件中的数据:1位置:2:0文本文件中的数据:1位置:0:1文本文件中的数据:1位置:1:1文本文件中的数据:1位置:2:1文本文件中的数据:1位置:0:2文本文件中的数据:1位置:1:2文本文件中的数据:1位置:2:2文本文件中的数据:1位置:0:3文本文件中的数据:1位置:1:3文本文件中的数据:1位置:2:3文本文件中的数据:1位置:0:4文本文件中的数据:1位置:1:4文本文件中的数据:1位置:2:4文本文件中的数据:1位置:0:5文本文件中的数据:1位置:1:5文本文件中的数据:1位置:2:5文本文件中的数据:1位置:0:6文本文件中的数据:1位置:1:6文本文件中的数据:1位置:2:6文本文件中的数据:1位置:0:7文本文件中的数据:1位置:1:7文本文件中的数据:1位置:2:7文本文件中的数据:1位置:0:8文本文件中的数据:1位置:1:8文本文件中的数据:1位置:2:8文本文件中的数据:1位置:0:9文本中的数据 文件:1位置:1:9文本文件中的数据:1位置:2:9文本文件中的数据:1位置:0:10文本文件中的数据:1位置:1:10文本文件中的数据:1
它遍历整个文件,但重新开始回到0,0。
位置:0:0文本中的数据文件:52
位置:1:0文本中的数据文件:52
位置:2:0文本中的数据文件:52
对于所有文字,我们都表示感谢,对于所有文字都尽量清晰一点,我们深表歉意。
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int width = 31;//declaring days or columns for array
int height = 3;//declaring information day and high and low
int data;
/* Code to read in txt file */
ifstream infile;
infile.open("weather.txt");
if (!infile) {
cerr << "Unable to open file C\n";
exit(1); // call system to stop
}
/* end code read text file */
int tempDay[height][width];
//PROBLEM WITH LOOP//
while (infile >> data) {
for (int i = 0; i < width; ++i) {
for (int j = 0; j < height ; ++j) {
tempDay[j][i] = data;
cout << "Location: " << j <<" : " << i << " Data in textFile: " <<data<<endl;
}
}
}
infile.close();
return 0;
}
由于您知道大小,因此应该可以:
const int width = 3;//declaring days or columns for array
const int height = 31;//declaring information day and high and low
// ..
int tempDay[height][width];
// ..
int i = 0;
while (infile >> tempDay[i][0] >> tempDay[i][1] >> tempDay[i][2]) // one line at a time
{
cout << tempDay[i][0] << ' ' << tempDay[i][1] << ' ' << tempDay[i][2] << endl;
i++;
}
如果文本文件如前所述并且有任何意外的字符,那么以下应该可以工作。 它与您的代码相似,不同之处在于它在for循环中检查意外的文件末尾(即文件中是否没有WIDTH
行)。
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main() {
const int WIDTH = 31;//declaring days or columns for array
const int HEIGHT = 3;//declaring information day and high and low
/* Code to read in txt file */
ifstream infile;
infile.open("weather.txt");
if (!infile) {
cerr << "Unable to open file\n" << endl;
exit(1); // call system to stop
}
/* end code read text file */
int tempDay[HEIGHT][WIDTH];
for (int i = 0; i < WIDTH; ++i) {
for (int j = 0; j < HEIGHT ; ++j) {
if (!(infile >> tempDay[j][i])) {
cerr << "Unexpected end of file\n" << endl;
exit(1); // call system to stop
}
cout << "Location: " << j <<" : " << i << " Data in textFile: " << tempDay[j][i] << endl;
}
}
infile.close();
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.