【发布时间】:2020-12-10 14:01:38
【问题描述】:
我有一个包含 5 行 10 列的 CSV 文件(每行包含 10 个小数形式的元素)。 我需要编写一个程序来打开和读取文件并取每一行的平均值。
void exercise3(){
FILE* Khoa_file=fopen("beeap20_knows_coding.csv", "r"); // attempt to open the file
double sum , ave; //making decimal varibales
int i; //i as int to to use for the sum calculation
if (Khoa_file==NULL){ //if the file opens nothiing (eg. not found)
perror("Error while opening file"); // print this as error
}
while(1){ //while true
int s; // variable in which content of file will be saved in
while((s=fgetc(Khoa_file)) !='\n' && s != EOF){ /*while loop, the idea was to use fgets to make a while loop . The fgets was supposed to take in data until it ecounters '\n',
then that would be 1 row and the next while loop would do the same thing (5x in total), but didnt work...*/
printf("%c", s); // print out the "gotten" values
}
if(s == EOF)
break; // when reaching the end of the file break out of the loop
printf("\t");
sum = 0;
while(1==fscanf(Khoa_file, "%d%*c", &i)){//%*c skip ',' and '\n'
sum += i;
}
ave = sum / 10 ;
printf("the average %f\n", ave);
}
fclose(Khoa_file);
}
这是我尝试的,但它完全是垃圾。请帮忙..
【问题讨论】:
-
您能解释一下发生了什么以及为什么会出错吗? “完全垃圾”有点不清楚。具体一点。