第十五周项目一 用二进制文件处理学生成绩
2015-06-10 20:26
549 查看
/* * Copyright (c) 2014, 烟台大学计算机学院 * All rights reserved. * 文件名称:test.cpp * 作 者:刘佳琦 * 完成日期:2015年 6 月 10日 * 版 本 号:v1.0 * * 问题描述:(1)定义学生类,其中包含学号、姓名、C++课、高数和英语成绩及总分数据成员,成员函数根据需要确定。 (2)读入学生的成绩,并求出总分,用对象数组进行存储。ASCII文件score.dat中保存的是100名学生的学号、姓名和C++课、高数和英语成绩。 (3)将所有数据保存到一个二进制文件binary_score.dat中,最后通过键盘输入你的信息,并写入到文件中(咱不谦虚,三科全100分,期末求好运)。 (4)为验证输出文件正确,再将binary_score.dat中的记录逐一读出到学生对象中并输出查看。 * 输入描述:增加的自己的成绩 * 程序输出:最后的结果 */ #include <iostream> #include <fstream> #include<string> #include<cstdlib> using namespace std; class Student { public: Student() {}; Student(int n,string na,int c,int m,int e):num(n),name(na),cpp(c),math(m),english(e) { total=c+m+e; } friend istream& operator>>(istream &in, Student &s); friend ostream& operator<<(ostream&, Student&); private: string name; int num; int math; int cpp; int english; int total; }; istream& operator>>(istream &in, Student &s) { in>>s.num>>s.name>>s.cpp>>s.math>>s.english; s.total=s.cpp+s.math+s.english; return in; } 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; int 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>>stud[i]; } infile.close(); 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 m(n,sname, scpp, smath, senglish); outfile.write((char*)&m, sizeof(m)); outfile.close(); Student s; ifstream infile2("binary_score.dat",ios::in|ios::binary); if(!infile2) { cerr<<"open error!"<<endl; exit(1); } while(1) { infile2.read((char*)&s, sizeof(s)); if(infile2.eof()) break; cout<<s; } infile2.close(); return 0; }
运行结果:
学习心得:
先是用的display函数,各种提示出错...于是我就改了重载,现在体会到了重载的好用...为了使得私有成员被访问,改成函数形式,要是再多点成员,真的不想改了...
相关文章推荐
- canjs基础教程之Components
- 足球裁判
- 为什么要在宏中使用 do{...}while(0) (转)
- hnuun 11544 小明的烦恼——找字符串(求环形字符串的最小最大字典序)
- DQS安装失败——系统重新引导是否处于挂起状态
- mysql表空间配置
- HNOI2015题解
- Linux环境下jdk的安装及环境变量的配置
- poj -- 3468
- hdu1142(最短路+记忆化搜索)
- (leetcode)Remove Duplicates from Sorted List
- Xcode6在iPhone5+iOS7模拟器上编译,上下有黑边问题
- System权限下进程遇到的问题以及如何降权启动进程
- 【VB.NET机房重构】SQLHelper--数据库小助手
- Majority Element
- 我们都爱大长腿
- Algorithms—22.Generate Parentheses
- XX项目总结
- uva 10397 Connect the Campus(最小生成树kruskal)
- 二进制bomb实验第三弹