我的目标是编写一个代码,将所有逗号分隔的数据从文本文件扫描到数组中。为确保成功,终端将以相同的方式打印数据。
数据文件的一个例子是
XXXX,location,yy,mm,dd,max,min
XXXX,86282,1990,3,1,24.9,18
XXXX,86282,1990,3,2,30.2,15.7
XXXX,86282,1990,3,3,28.2,17.2
XXXX,86282,1990,3,4,28.6,18
XXXX,86282,1990,3,5,25.2,17.5
XXXX,86282,1990,3,6,19.2,15
我所做的就是这个
int i = 0;
int a_location[50000];
int a_yy[50000];
int a_mm[50000];
int a_dd[50000];
double a_max[50000];
double a_min[50000];
int location, yy, mm, dd;
double max, min;
while((c=getchar()) != EOF){
while(scanf("XXXX,%d,%d,%d,%d,%lf,%lf\n",&location, &yy, &mm, &dd, &max, &min) == 6){a_location[i] = location;
a_yy[i] = yy;
a_mm[i] = mm;
a_dd[i] = dd;
a_max[i] = max;
a_min[i] = min;
i+=1;
}
}
for(i = 1; i < nlines; i++){
printf("%d,%d,%d,%d,%0.3f,%0.3f\n", a_location[i], a_yy[i], a_mm[i], a_dd[i], a_max[i], a_min[i]);
}
终端显示此
./scan.exe<datafile.txt
0,0,0,0,0.000,0.000
0,0,0,0,0.000,0.000
0,0,0,0,0.000,0.000
0,0,0,0,0.000,0.000
0,0,0,0,0.000,0.000
0,0,0,0,0.000,0.000
我想弄清楚出了什么问题。
答案 0 :(得分:0)
您得到的结果是因为您要保存第一行的值,这些值是数组数组中的字符串。
您可以忽略第一行,然后处理以下行,以防格式化。
int i = 0;
int a_location[50000];
int a_yy[50000];
int a_mm[50000];
int a_dd[50000];
double a_max[50000];
double a_min[50000];
int location, yy, mm, dd;
double max, min;
scanf("XXXX,location,yy,mm,dd,max,min\n");
while(scanf("XXXX,%d,%d,%d,%d,%lf,%lf\n",&location, &yy, &mm, &dd, &max, &min) == 6)
{
a_location[i] = location;
a_yy[i] = yy;
a_mm[i] = mm;
a_dd[i] = dd;
a_max[i] = max;
a_min[i] = min;
i++;
}
for(i = 0; i < nlines; i++){
printf("%d,%d,%d,%d,%0.3f,%0.3f\n", a_location[i], a_yy[i], a_mm[i], a_dd[i], a_max[i], a_min[i]);
如果遵循此方法,for的索引必须从0开始。 问候。