第十五周 项目一--用二进制文件处理学生成绩
2015-06-21 09:42
686 查看
问题及代码:
/* * Copyright (c) 2015, 烟台大学计算机学院 * All rights reserved. * 文件名称:Project4.cpp * 作 者:吴胜男 * 完成日期:2015年6月21日 * 版 本 号:v1.0 * * 问题描述: (1)定义学生类,其中包含学号、姓名、C++课、高数和英语成绩及总分数据成员,成员函数根据需要确定。 (2)读入学生的成绩,并求出总分,用对象数组进行存储。ASCII文件score.dat中保存的是100名学生的学号、姓名和C++课、高数和英语成绩。 (3)将所有数据保存到一个二进制文件binary_score.dat中,最后通过键盘输入你的信息,并写入到文件中(咱不谦虚,三科全100分,期末求好运)。 (4)为验证输出文件正确,再将binary_score.dat中的记录逐一读出到学生对象中并输出查看。 (5)用BinaryViewer命令查看二进制文件 * 输入描述:略 * 程序输出:略 */ #include <iostream> #include <fstream> #include <cstring> #include <cstdlib> using namespace std; class Student { private: int num; string name; double cpp; double math; double english; double total; public: Student(int n=0,string na="0",double c=0,double m=0,double e=0); void setvalue(int n,string na, double c, double m, double e); friend ostream& operator<<(ostream&, Student&); }; Student::Student(int n,string na,double c,double m,double e) { num=n; name=na; cpp=c; math=m; english=e; total=m+c+e; } void Student::setvalue(int n,string nam, double c, double m, double e) { num=n; name=nam; cpp=c; math=m; english=e; total=c+m+e; } ostream& operator<<(ostream& out, Student& s) { out<<s.num<<" "<<s.name<<" "<<s.cpp<<" "<<s.math<<" "<<s.english<<" "<<s.total<<endl; return out; } int main() { Student stu[50]; int i; int num; string lname; double lcpp, lmath, lenglish; ifstream infile("score.dat",ios::in); if(!infile) //测试是否成功打开 { cerr<<"open error!"<<endl; exit(1); } for(i=0;i<45;i++) { infile>>num>>lname>>lcpp>>lmath>>lenglish; stu[i].setvalue(num,lname,lcpp,lmath,lenglish); } infile.close(); ofstream outfile("binary_score.dat",ios::out|ios::binary);//二进制文件 if(!outfile) { cerr<<"open error!"<<endl; exit(1); } for(i=0;i<45;i++) { outfile.write((char*)&stu[i], sizeof(stu[i]));//注意write函数 } cout<<"输入你的信息:"; cin>>num>>lname>>lcpp>>lmath>>lenglish; Student my(num,lname,lcpp,lmath,lenglish); outfile.write((char*)&my, sizeof(my));//注意write函数 outfile.close(); Student stud; ifstream infile1("binary_score.dat",ios::in|ios::binary);//将binary_score.dat中的记录逐一读出到学生对象中并输出查看。 if(!infile1) { cerr<<"open error!"<<endl; exit(1); } while(1) { infile1.read((char*)&stud, sizeof(stud)); if(infile1.eof()) break; cout<<stud; } infile1.close(); return 0; }运行结果:知识点总结:第一个for循环是从文件中读取数据并计算总成绩,第二个for是输出数据。学习心得:开始看了小伙伴的程序,有疑惑,讨论之后觉的小伙伴的程序可以删除一些不必要的函数。感觉棒棒哒!
相关文章推荐