第十六周项目 用二进制文件处理学生成绩
2016-06-18 14:02
423 查看
/* *Copyright(c) 2016, 烟台大学计算机与控制工程学院 *All rights reserved. *文件名称:main.cpp *作 者:李德坤 *完成日期:2016年6月18日 *版本号:v1.0 * *问题描述:用二进制文件处理学生成绩 *输入描述:无 *输出描述:无 */ #include <fstream> #include<iostream> #include<cstring> #include<cstdlib> using namespace std; //(一)定义学生类 class Student { public: Student(){}; Student(int n, string nam, double c, double m, double e):num(n),name(nam),cpp(c),math(m),english(e){total=c+m+e;} void set_value(int n,string nam, double c, double m, double e); string get_name(){return name;} double get_cpp(){return cpp;} double get_math(){return math;} double get_english(){return english;} double get_total(){return total;} void set_cpp(double c){cpp=c;} void set_math(double m){math=m;} void set_english(double e){english=e;} void set_total(double t){total=t;} friend ostream& operator<<(ostream&, Student&); private: int num; string name; double cpp; double math; double english; double total; }; void Student::set_value(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 stud[100]; //stud[100]为保存数据的对象数组 int i,n; string sname; double scpp, smath, senglish; //(二)读入学生的成绩,并求出总分,用对象数组进行存储。 ifstream infile("score.dat",ios::in); //以输入的方式打开文件,ASCII文件 if(!infile) //测试是否成功打开 { cerr<<"open error!"<<endl; exit(1); } for(i=0;i<100;i++) { infile>>n>>sname>>scpp>>smath>>senglish; stud[i].set_value(n,sname, scpp, smath, senglish); } infile.close(); //(三)将所有数据保存到一个二进制文件binary_score.dat中 ofstream outfile("binary_score.dat",ios::out|ios::binary); if(!outfile) { cerr<<"open error!"<<endl; exit(1); } for(i=0;i<100;i++) { outfile.write((char*)&stud[i], sizeof(stud[i])); } //(三)最后在文件中写入你自己的各科成绩 cout<<"输入你自己的信息:"; cin>>n>>sname>>scpp>>smath>>senglish; Student me(n,sname, scpp, smath, senglish); outfile.write((char*)&me, sizeof(me)); outfile.close(); //(四)为验证输出文件正确,再将binary_score.dat中的记录逐一读出到学生对象中并输出查看。 Student s; ifstream infile2("binary_score.dat",ios::in|ios::binary); if(!infile2) { cerr<<"open error!"<<endl; exit(1); } while(true) { infile2.read((char*)&s, sizeof(s)); if(infile2.eof()) break; cout<<s; } infile2.close(); return 0; }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性