#include <iostream> #include <fstream> #include <cstdlib> //在codeblocks下,exit(1)需要这个头文件 using namespace std; struct Student { char num[13]; //尽管都是由数字构成,但看作为字符更合适。 char name[10]; //每个汉字占两个字节,中国人的名字,5个汉字够用 int cpp; int math; int english; int grade; struct Student *next; //指向下一节点的指针 }; int main( ) { Student *head=NULL,*p,*q; int stuNum=0,i; int sum=0,ave; //用于求平均 ifstream infile("score.txt",ios::in); //以输入的方式打开文件 if(!infile) //测试是否成功打开 { cerr<<"open error!"<<endl; exit(1); } //下面从文件中读取数据,同时建立动态链表,并为求总分之和 stuNum=0; while(!infile.eof()) { p = new Student; infile>>p->num>>p->name>>p->cpp>>p->math>>p->english; p->grade = p->cpp + p->math + p->english; sum+=p->grade; p->next=NULL; if (stuNum==0) head=p; //是第一个节点 else q->next=p; //用q记录刚刚产生的结点,如果有下一个,需要q将之连起来 ++stuNum; q=p; } infile.close(); //求平均成绩 ave=sum/stuNum; cout<<"总分平均为:"<<ave<<endl; //依次输出所有总分高于平均总分且没有挂科的同学的学号、姓名、总分。 cout<<"总分高于平均总分且没有挂科的同学有:"<<endl; p=head; i=1; while(p!=NULL) { if(p->grade>=ave&&p->cpp>=60&&p->math>=60&&p->english>=60) { cout<<i<<" "<<p->num<<" "<<p->name<<" "<<p->grade<<endl; i++; } p=p->next; } return 0; }