#include<stdio.h> #include<stdlib.h> #define N 30 typedef struct student /*定義儲存學(xué)生成績信息的數(shù)組*/ { char *name; int chinese; int maths; int phy; int total; }ST; main() { ST a[N]; /*存儲N個學(xué)生信息的數(shù)組*/ FILE *fp; void (*process[3])(ST *)={Output,Bubble,Find}; /*實現(xiàn)相關(guān)功能的三個函數(shù)*/ int choice,i=0; Show(); printf("\nChoose:\n?"); scanf("%d",&choice); while(choice>=0&&choice<=2) { fp=fopen("aa.dat","rb"); for(i=0;i<N;i++) fread(&a[i],sizeof(ST),1,fp); /*把文件中儲存的信息逐個讀到數(shù)組中去*/ fclose(fp); (*process[choice])(a); /*前面提到的指向函數(shù)的指針,選擇操作*/ printf("\n"); Show(); printf("\n?"); scanf("%d",&choice); } } void Show() { printf("\n****Choices:****\n0.Display the data form\n1.Bubble it according to the total score\n2.Search\n3.Quit!\n"); } void Output(ST *a) /*將文件中存儲的信息逐個輸出*/ { int i,t=0; printf("Name Chinese Maths Physics Total\n"); for(i=0;i<N;i++) { t=a[i].chinese+a[i].maths+a[i].phy; a[i].total=t; printf("%4s%8d%8d%8d%8d\n",a[i].name,a[i].chinese,a[i].maths,a[i].phy,a[i].total); } } void Bubble(ST *a) /*對數(shù)組進行排序,并輸出結(jié)果*/ { int i,pass; ST m; for(pass=0;pass<N-1;pass++) for(i=0;i<N-1;i++) if(a[i].total<a[i+1].total) { m=a[i]; /*結(jié)構(gòu)互換*/ a[i]=a[i+1]; a[i+1]=m; } Output(a); } void Find(ST *a) { int i,t=1; char m[20]; printf("\nEnter the name you want:"); scanf("%s",m); for(i=0;i<N;i++) if(!strcmp(m,a[i].name)) /*根據(jù)姓名匹配情況輸出查找結(jié)果*/ { printf("\nThe result is:\n%s, Chinese:%d, Maths:%d, Physics:%d,Total:%d\n",m,a[i].chinese,a[i].maths,a[i].phy,a[i].total); t=0; } if(t) printf("\nThe name is not in the list!\n"); } |