//並按照下列各式把信息存入到customer.txt中:
//0001 Kate 5 822.8
//0002 Jame 7 2761.9
//2011.1.11 11:37
#include<stdio.h>
#include<math.h>
#define CST_NUM 10//宏定義客戶數目
struct customer
{
int num;
char name[20];
int amount;
float value;
}cst[CST_NUM];//定義結構體customer,並聲明結構體數組cst[CST_NUM].
void printline(void);
void sort_cst(struct customer[],int);
void print_cst(struct customer[],int);
void main(void)
{
FILE *f1;//聲明文件指針
int h=sin(0);//為編譯器裝載float類型
int i;
for(i=0;i<CST_NUM;i++)//從鍵盤讀取客戶信息
{
printline();
printf("請輸入第%d名顧客的編號",i+1);
scanf("%d",&cst[i].num);
putchar('\n');
fflush(stdin);//清流
printf("請輸入第%d名顧客的姓名",i+1);
scanf("%s",cst[i].name);
putchar('\n');
fflush(stdin);//清流
printf("請輸入第%d名顧客的商品數量",i+1);
scanf("%d",&cst[i].amount);
putchar('\n');
printf("請輸入第%d名顧客的商品總額",i+1);
scanf("%f",&cst[i].value);
putchar('\n');
fflush(stdin);//清流
}
sort_cst(cst,CST_NUM);//客戶信息排序
print_cst(cst,CST_NUM);//將客戶信息輸出至屏幕
f1=fopen("customer.txt","w");//打開文件
fprintf(f1,"客戶編號 客戶姓名 商品數量 商品總額\n");
for(i=0;i<CST_NUM;i++)
{
fprintf(f1,"%5d%12s%10d%10.1f\n",cst[i].num,cst[i].name,cst[i].amount,cst[i].value);//存入客戶信息
}
fclose(f1);//關閉文件
getch();
}
void sort_cst(struct customer cst[],int cst_num)//自定義函數:客戶信息排序
{
int i,j;
struct customer temp;
for(i=0;i<cst_num;i++)
{
for(j=0;j<cst_num;j++)
{
if(cst[i].value>cst[j].value)
{
temp=cst[i];
cst[i]=cst[j];
cst[j]=temp;
}
} }
}
void print_cst(struct customer cst[],int cst_num)//自定義函數:客戶信息顯示
{
int i;
printline();
printf("客戶編號 客戶姓名 商品數量 商品總額\n");
for(i=0;i<cst_num;i++)
{
printf("%5d",cst[i].num);
printf("%12s",cst[i].name);
printf("%10d",cst[i].amount);
printf("%10.1f\n",cst[i].value);
}
printline();
}
void printline(void)//自定義函數:畫線
{
int i;
printf("\n");
for(i=0;i<50;i++)
{
printf("_");
}
printf("\n");
}