【发布时间】:2021-04-30 01:28:10
【问题描述】:
我对 C 有点陌生。 我正在尝试制作一个购物车应用程序,该程序从包含产品和价格的 txt 文件中读取数据,由空格分隔。 然后在一个新行中放置另一个产品和一个价格(也由空格分隔)。 然后在另一个“bill.txt”文本文件中输出账单。 示例:
取自文件 (products.txt) 的输入:
Bread 2.78
cheese 4.59
vegetables 1.99
bread 1.99
Milk 0.56
cheese 2.79
输出写入另一个文件(bill.txt):
bread : 4.77 , 2 products, average-price: 2.38
cheese: 7.38 , 2 products, average-price: 3.69
milk: 0.56 , 1 products, average-price: 0.56
vegetables: 1.99 , 1 products, average-price: 1.99
total : 14.70
我的主要问题是我对如何将文本文件中的面包等重复产品的总和相加并将它们添加为数量感到困惑!面包在输入中被写入两次,但数量为 2。
通常在 java 之类的语言中,我会使用 ArrayList 并轻松解决它,但由于 C 没有 Arraylist,该怎么办?
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
int count;
struct Product
{
char productName[30];
double price;
};
struct Product p1;
int main()
{
double total = 0;
//input file
FILE *fp;
fp = fopen("products.txt","r");
//output file
FILE *fp1 = fopen("bill.txt","w");
if (fp == NULL || fp1 ==NULL)
{
perror("files didn't open");
}
printf("this input was written in file:\n");
while(1)
{
fscanf(fp,"%s %d",&p1.productName,&p1.price);
total = total + p1.price;
fprintf(fp1,"%s:\t%d, \n",p1.productName,p1.price);
printf("%s:\t%d, \n",p1.productName,p1.price);
if (feof(fp))
{
fprintf(fp1,"Total: %d",total);
break;
}
}
printf("total: %d", total);
return 0;
}
有什么想法吗?
【问题讨论】:
-
你知道你有多少产品吗?或上限?如果不是,那么您必须使您的产品列表可调整大小。另一方面,如果您事先确切知道您拥有的产品,您可以让它变得更简单。
-
256 是一个不错的选择 ;-) 虽然我看到我在下面选择了一个无聊的 100!对于动态分配,有两个有趣的地方。在相关示例中,静态产品名称长度设置为 30。然后是产品列表的大小。首先使用静态值,让代码正常工作,然后随着有趣的练习更改为对产品列表和产品名称使用动态分配。
-
所以你必须做不区分大小写的比较?