第15周【项目1-用二进制文件处理学生成绩】
2015-06-13 16:28
507 查看
#include <iostream> #include <fstream> #include <cstring> #include <cstdlib> using namespace std; class Student { public: Student(){}; Student(int n, string nam, double c, double m, double e); void set_value(int n,string nam, double c, double m, double e); 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 &s); private: int num; string name; double cpp; double math; double english; double total; }; 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 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]; int i,n; string sname; double scpp, smath, senglish; //(二)读入学生的成绩,并求出总分,用对象数组进行存储。 ifstream infile("score.dat",ios::in); 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])); } //(三)最后在文件中写入你自己的各科成绩 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; }
相关文章推荐
- HTML5表格基础语法
- SVN corestone不支持.a文件的上传解决办法
- java使用poi读取ppt文件和poi读取excel、word示例
- redis 数据类型及操作方法
- adb server is out of date. killing... 的解决办法
- 配置到 Framework GAC(Global Assembly Cache) Assembly
- 卡巴斯基遭攻击 Duqu 2.0 翻译
- 普通的朋友,淡淡的生活
- VM下Linux网卡丢失(pcnet32 device eth0 does not seem to be ...)解决方案
- C++代理实现
- 用它解决大问题啦,STRACE应用
- Java位运算总结:位运算用途广泛《转》
- 从无头单链表中删除节点
- kd树(k-dimensional tree)(1)
- 线程池相关
- 九度OJ-题目1508:把字符串转换成整数
- js页面跳转整理
- C++学习笔记之---boolalpha
- 16-m-3Sum Closest
- 使用Apache POI将ppt截屏成png格式(+背景和图片)