CSV文件行平均值(C)

CSV文件行平均值(C),c,csv,average,stdio,C,Csv,Average,Stdio,我有一个CSV文件,有5行10列(每行包含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;

我有一个CSV文件,有5行10列(每行包含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);
}

这是我尝试过的,但它完全是垃圾。请帮助..

只需执行以下操作:

int val[10];
while( 10 == scanf("%d%d%d%d%d%d%d%d%d%d ", val, val + 1, val + 2 ...) ){
...
}
尽管查看代码时,您的输入似乎是逗号分隔的,因此您可能更喜欢:

while( 10 == scanf("%d ,%d ,%d ,%d ,%d ,%d ,%d ,%d ,%d ,%d ", ...

这不会验证输入是否为每行10个数据条目,但如果您的输入遵循每行只有9个逗号的约定,则它确实有效。此外,它还可以处理“5、\n6、…”等输入,其中10个数据点跨越多行。根据需要删除格式字符串中的空白。如果您关心精确的输入格式,并希望验证换行符的出现,则可以使用
fgets
或将格式字符串中的尾随空格替换为
%c
,并验证scanf是否读取显式
\n
。但是,简单地构造while循环,用一个
scanf
一次读取10个数据元素,可能就足以满足您的需要了。

您能解释一下发生了什么以及为什么出错吗?“完全的垃圾”有点不清楚。具体点。谢谢,先生,我试试看