我有一个我们必须处理的文本文件,格式为
dd - 日 mm - 月 yyyy - 年 x,y,w,z - 温度
dd,mm,yyyy,x,y,z,w
1,1,2010,20.8,19.2,29.3,20.9
2,1,2010,22.5,15.5,30.7,23.3
3,1,2010,21.4,14.5,21.5,18.9
4,1,2010,27.6,13.4,23.9,18.2
5,1,2010,25,16,26.1,18.3
6,1,2010,23.6,16.1,27.6,21.8
...
29,1,2010,23.5,17.5,30.2,19.6
30,1,2010,36.2,13.4,27.3,20.5
31,1,2010,37.2,17.1,26.6,21.5
1,2,2010,24.9,16.9,27.7,22.6
2,2,2010,35.2,16.7,27.7,22.7
3,2,2010,34.8,21.6,27.3,21.4
...
1,12,2010,26.6,16.5,20.1,17.2
2,12,2010,27.2,17.2,24.3,18.5
3,12,2010,30,17.2,24.4,19.8
...
30,12,2010,23.7,14.2,26.5,20
31,12,2010,41.1,14.9,27.2,21.4
我们没有被教导使用数组来处理这些数据,只有函数、if/else 语句、循环(while/for)和操作。
我需要分别处理每个月的数据。我的主要代码包含在一个while (scanf("%d,%d,%d,%f,%f,%f,%f", &dd, &mm, &yyyy, &x, &y, &z, &w) ==7) {}
循环中。
下面是我的代码:
while (scanf("%d,%d,%d,%f,%f,%f,%f", &dd, &mm, &yyyy, &melmax, &melmin, &sydmax, &sydmin) ==7) {
if (totallinesread==0) {
currentmonth = mm;
printf("Stage 4\n=======\n");
}
if (mm == currentmonth) {
daysinmonthcounted+=1;
/*other totals*/
}else if (mm !=currentmonth){
/*can execute code here as needed such as generating graphs etc*/
printf("0----+----1----+----2----+----3----+----4----+----5 (x 10, degrees C)\n");
printf("%d\n", daysinmonthcounted);
/* make new currentmonth = mm, reset days counted = 1 */
currentmonth = mm;
daysinmonthcounted = 1;
}
totallinesread+=1;
}
输出:
0----+----1----+----2----+----3----+----4----+----5 (x 10, degrees C)
31
0----+----1----+----2----+----3----+----4----+----5 (x 10, degrees C)
28
0----+----1----+----2----+----3----+----4----+----5 (x 10, degrees C)
31
0----+----1----+----2----+----3----+----4----+----5 (x 10, degrees C)
30
0----+----1----+----2----+----3----+----4----+----5 (x 10, degrees C)
31
0----+----1----+----2----+----3----+----4----+----5 (x 10, degrees C)
30
0----+----1----+----2----+----3----+----4----+----5 (x 10, degrees C)
31
0----+----1----+----2----+----3----+----4----+----5 (x 10, degrees C)
31
0----+----1----+----2----+----3----+----4----+----5 (x 10, degrees C)
30
0----+----1----+----2----+----3----+----4----+----5 (x 10, degrees C)
31
0----+----1----+----2----+----3----+----4----+----5 (x 10, degrees C)
30
(Note missing december 31 days at the end)
我发现这可以按我的意愿工作和输出(目前只打印每个月的总天数),但它在最后一个月完全跳过了。我认为它与文件结尾(EOF)有关,因为 if 语句没有下一个“mm”值要使用(currentmonth != mm
),所以它停止并且不允许我处理 12 月的任何额外计算代码.
有什么办法可以做到这一点吗?我读过scanf(EOF) = -1
,应该使用currentmonth != mm
哪个?
可以假定数据文本文件没有错误或重复条目,并且是升序排列的。
任何帮助,将不胜感激。
谢谢!