【问题标题】:CSV file row average in CC中的CSV文件行平均值
【发布时间】: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);
}

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

【问题讨论】:

  • 您能解释一下发生了什么以及为什么会出错吗? “完全垃圾”有点不清楚。具体一点。

标签: c csv average stdio


【解决方案1】:

只需执行以下操作:

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 个数据元素可能就足以满足您的需求。

【讨论】:

    猜你喜欢
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    • 2015-12-01
    • 2016-08-03
    • 1970-01-01
    • 2021-04-06
    • 2021-12-13
    • 1970-01-01
    相关资源
    最近更新 更多