首页 > 解决方案 > 在 C 中格式化

问题描述

我不断收到格式错误,我不确定如何调整我的代码。

int main()
{
    FILE* fp=fopen("food.txt","r");
    float costs_2018[10];
    float costs_2020[10];
    char* name[1000][10];
    char* quantity[1000][10];
    fscanf(fp,"%s %s %s %s",&name[0], &quantity[0], &costs_2018[0], &costs_2020[0]);
    for (int i=0;i<10;i++)
    {
        fscanf(fp,"%s %d%*s %f %f",&name[i],&quantity[i],&costs_2018[i],&costs_2020[i]);
    }
    printf("total cost in 2018 is = %f",calculate_total_cost(costs_2018));
    printf("\ntotal cost in 2020 is = %f",calculate_total_cost(costs_2020));
    printf("\naverage cost in 2018 is = %f",calculate_total_average(costs_2018));
    printf("\naverage cost in 2020 is = %f",calculate_total_average(costs_2020));
    printf("\nDifference in total price between 2018 and 2020 is = %f",calculate_total_cost(costs_2018)-calculate_total_cost(costs_2020));
    printf("\nDifference in average price between 2018 and 2020 is = %f",calculate_total_average(costs_2018)-calculate_total_average(costs_2020));
    return 0;
}

在我的两条“fscanf”行上,我都遇到了格式错误。第一个 fscanf 行 name,quantity,costs_2018,costs2019 带有红色下划线。第二个 fscanf 行只是名称和数量带有红色下划线。

标签: cclionc11

解决方案


看起来你想要 10char[1000]namequantity

像这样声明:

char name[10][1000];
char quantity[10][1000];

然后将参数传递给scanf应该像这样完成:

if(fscanf(fp,"%999s %999s %f %f", name[i], quantity[i],
                                  &costs_2018[i], &costs_2020[i]) == 4)
{
    /* success */
} else {
    /* failure */
}

当作为参数传递给函数时,所有数组(例如char[1000]at 的数组)都会衰减为指针,这就是为什么不应该使用的原因。name[i]&name[i]


推荐阅读