c - 在 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 行只是名称和数量带有红色下划线。
解决方案
看起来你想要 10char[1000]
的name
和quantity
。
像这样声明:
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]
推荐阅读
- socket.io - flask_socketio 并发使用 eventlet
- java - Quartz 调度器集群
- c# - 基于 ASP.NET Core 中的 Controller 需要条件
- facebook - 检查是否存在 facebook 永久链接消息
- c# - MongoDB中upsert期间的并发问题
- haskell - 如何使用列表理解创建多个/不同的自定义类型?
- amazon-web-services - 无服务器框架 Cognito Userpool Pre Token Generator
- single-sign-on - 使用 Angular 创建 Outlook 加载项
- ruby-on-rails - Ruby 中的 Active Record 搜索特定文本模式
- reactjs - 如何从已弃用的切换
在 react-18next 中?