[英]Reading from a text file into a 2D array representing a month
我需要从文本文件中读取温度列表。
这是文本的外观。 第一行中的“ 6”表示该月份列出的周数。 列是从星期天开始的星期几,“-10”是占位符,表示该月的该职位没有一天。 在示例文件中,月份从星期五开始,在星期日结束。
6
-10 -10 -10 -10 -10 8.7 7.8
9.2 13.7 16.1 18.1 18.6 14.7 15.7
14.5 16.4 17.9 20.5 14.9 16.4 20.3
21.2 15.1 10.4 11.8 17 17.3 13.8
9.9 7.8 6.4 9.4 9.4 13 16
17.9 -10 -10 -10 -10 -10 -10
我的函数需要从文件中读取温度,然后将其作为2D数组返回。
double ** readtemp(string filename, int &weeks)
{
ifstream infile(filename);
if (!infile)
exit(1);
infile >> weeks;
double ** address = new double *[weeks], read_test;
for (int i = 0; i < weeks; i++)
{
address[i] = new double[7];
for (int j = 0; j < 7; j++)
{
if (infile >> read_test)
address[i][j] = read_test;
else
address[i][j] = -10;
}
}
infile.close();
return address;
}
我在阅读不从星期日开始的一个月时遇到问题。 当月份不是从星期日开始时,数组将“拉”所有其他日期。 我无法在月初缺少的那些天插入“ -10”。
没有任何“丢失天数”,因为对于没有数据的天数,您已经在文本文件中输入-10
。 只需读入它们即可,无需特别注意数字-10
。
double ** readtemp(string filename, int &weeks)
{
ifstream infile(filename);
if (!infile)
exit(1);
infile >> weeks;
double ** address = new double *[weeks], read_test;
for (int i = 0; i < weeks; i++)
{
address[i] = new double[7];
for (int j = 0; j < 7; j++)
{
if (infile >> read_test)
address[i][j] = read_test;
else
throw runtime_error("Read failed.");
}
}
infile.close();
return address;
}
有趣的问题,但是理解问题的确切根源的基本问题是: 当月份不是从星期日开始时,数组将“拉”所有其他日期 。 鉴于该语句是模棱两可的,并且还可以通过添加以下辅助函数来测试这些行:
void print(double **data , int weeks , int cols)
{
string days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
for (int x = 0; x < weeks; x++)
{
cout << "On the #" << (x + 1) << " Week\r\n";
for (int y = 0; y < cols; y++)
{
cout << "---Temp On " << days[y] + " was: " << data[x][y] << "---\r\n";
}
cout << endl;
}
}
真的无法分辨出您在哪里错了吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.