我是靠谱客的博主 优美蜻蜓,这篇文章主要介绍从txt文件向程序中读入数据并处理,现在分享给大家,希望可以做个参考。

商品销售记录包括商品id,商品名称,商品出售日期(结构体:包括年,月,日),单价,数量。现有一文件sell.txt里面有10条商品销售记录,每条记录格式如下:1 袜子 2021-12-26 5 1。

请读出该文件内容,然后按照出售日期降序排序后输出到屏幕上,并计算出这批商品的总金额,以及均价并输出。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <stdio.h> #include <stdlib.h> #define SIZE 10 struct date{ int year; int month; int day; }; struct goods{ char no[10]; char name[20]; struct date date; int price; int count; }goods[SIZE]; void sort(struct goods p[]){ struct goods temp; int i,j; for(i=0;i<SIZE-1;i++){ for(j=i+1;j<SIZE;j++){ if(p[j].date.year>p[i].date.year){ temp=p[j]; p[j]=p[i]; p[i]=temp; }else if(p[j].date.year==p[i].date.year&&p[j].date.month>p[i].date.month){ temp=p[j]; p[j]=p[i]; p[i]=temp; }else if(p[j].date.year==p[i].date.year&&p[j].date.month==p[i].date.month&&p[j].date.day>p[i].date.day){ temp=p[j]; p[j]=p[i]; p[i]=temp; } } } } void main(){ int i,sum=0,count=0; FILE *fp; if((fp=fopen("E:\sell.txt","r"))==NULL){ printf("Open file error!n"); exit(0); } for(i=0;i<SIZE;i++){ fscanf(fp,"%s %s %d-%d-%d %d %dn",goods[i].no,goods[i].name,&goods[i].date.year,&goods[i].date.month,&goods[i].date.day,&goods[i].price,&goods[i].count); sum+=goods[i].price*goods[i].count; count+=goods[i].count; } fclose(fp); sort(goods); for(i=0;i<SIZE;i++) printf("%s %s %d-%d-%d %d %dn",goods[i].no,goods[i].name,goods[i].date.year,goods[i].date.month,goods[i].date.day,goods[i].price,goods[i].count); printf("n商品总额为:%d,均价:%dn",sum,sum/count); }

最后

以上就是优美蜻蜓最近收集整理的关于从txt文件向程序中读入数据并处理的全部内容,更多相关从txt文件向程序中读入数据并处理内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(51)

评论列表共有 0 条评论

立即
投稿
返回
顶部