第十四周 项目2-用文件保存的学生名单
2015-06-10 15:37
169 查看
/* * Copyright (c) 2014, 烟台大学计算机学院 * All rights reserved. * 文件名称:test.cpp * 作 者:呼亚萍 * 完成日期:2015年6月10日 * 版 本 号:v1.0 * * 问题描述: 文件score.dat中保存的是若干名学生的姓名和C++课、高数和英语成绩。定义学生类,其中包含姓名、C++课、高数和英语成绩及总分数据成员。用对象数组进行存储学生的成绩,读入成绩并计算总分;将总分高于平均总分且没挂科的同学的信息保存到文件pass_score.dat中。 * 程序输入:相应的程序 * 程序输出:对应得结果 */ #include<iostream> #include<fstream> #include<cstdlib> #include<cstring> using namespace std; class Student { public: Student(){}; ~Student(); double get_total(); static int get_stu_num(); static double get_total_sum(); friend istream& operator>>(istream&,Student&); friend ostream&operator<<(ostream&,Student&); bool pass();//返回是否全部课程全过 private: string name; double cpp; double math; double english; double total; static int stu_num; //学生人数,处理为类的静态成员合适 static double total_sum; //学生总分和 }; int Student::stu_num=0; double Student::total_sum=0; Student::~Student() { total_sum-=total; stu_num--;//析构函数的释放 } double Student::get_total() { return total; } int Student::get_stu_num()//静态函数定义是需注明static { return stu_num; } double Student::get_total_sum() { return total_sum; } istream& operator>>(istream&in,Student&s) { in>>s.name>>s.cpp>>s.math>>s.english; s.total=s.cpp+s.math+s.english; Student::stu_num++;//在读入数据时,用静态成员记录下学生总人数和总分和 Student::total_sum+=s.total; return in; } ostream&operator<<(ostream&out,Student&s) { out<<s.name<<'\t'; out<<s.cpp<<'\t'; out<<s.math<<'\t'; out<<s.english<<'\t'; out<<s.total<<'\t'; return out; } bool Student::pass() { return (cpp>=60&&math>=60&&english>=60); } int main( ) { Student stud[200],t; //stud[200]为保存数据的对象数组 string sname; double total_avg; int i=0; fstream infile,outfile; infile.open("score.dat",ios::in);//从文件score.dat中读入数据,保存到对象数组中 if(!infile) { cout<<"score.dat can't open"<<endl; exit(1); } while(!infile.eof()) { infile>>stud[i++]; } infile.close(); outfile.open("pass_dat.dat",ios::out);//总分高于平均总分且没挂科的同学的信息保存到文件pass_score.dat中 if(Student::get_stu_num()>0) { total_avg=Student::get_total_sum()/Student::get_stu_num(); if(!outfile) { cout<<"can't open the file"<<endl; exit(1); } for(i=0; i<Student::get_stu_num(); ++i) { if(stud[i].get_total()>=total_avg&&stud[i].pass()) { outfile<<stud[i]<<endl; } } outfile.close(); cout<<"请到pass_score.dat文件中查看总分高于平均总分且没有挂科的同学成绩"<<endl; return 0; } }
运算结果:
知识点总结:
使用文件保存数据,infile与outfile的再应用。
学习心得;
在新的学习过程中发现对过去知识的遗忘,需要加强复习!
相关文章推荐
- 内存对齐
- Python基础(下)
- 关于iOS tabelView隐藏多余的cell
- 文件间的编译依存关系
- 文件间的编译依存关系 分类: C/C++ 2015-06-10 15:37 34人阅读 评论(0) 收藏
- 获取到EditText里面的值
- php使用Jpgraph绘制复杂X-Y坐标图的方法
- 学习Ocaml(2)---基础
- 栈(一)
- RMAN 同机复制数据库
- Java线程(篇外篇):阻塞队列BlockingQueue
- mybatis对mysql进行分页
- 漫画:为什么不能打断程序员?
- 前端开发APP,从HBuilder开始~ 【转】
- Java创建一个临时文件方法
- Caused by: java.sql.SQLException: Incorrect integer value: '' for column 'clientId' at row 41
- 【hbase】Configuring HBase Authorization
- 写数据到CSV文件时,数字字符串的问题
- CornerStone上传静态库(.a文件)
- 安装Virtualbox与Hyper-v冲突,关闭Hyper-V