您的位置:首页 > 其它

第十六周项目1- 用二进制文件处理学生成绩

2014-06-10 17:00 513 查看
/*
*程序的版权和版本声明部分:
*Copyright(c)2014,烟台大学计算机学院学生
*All rights reserved.
*文件名称:
*作者:田成琳
*完成日期:2014 年 6 月 10 日
*版本号:v1.0
*对任务及求解方法的描述部分:
*输入描述: 自己的学号,姓名,三科成绩及总成绩

*问题描述:
(1)定义学生类,其中包含学号、姓名、C++课、高数和英语成绩及总分数据成员,成员函数根据需要确定。
(2)读入学生的成绩,并求出总分,用对象数组进行存储。
(3)将所有数据保存到一个二进制文件binary_score.dat中,最后通过键盘输入你的信息,并写入到文件中。
(4)为验证输出文件正确,再将binary_score.dat中的记录逐一读出到学生对象中并输出查看。
*程序输出:学生学号,姓名,成绩
*问题分析:
*算法设计:
*/
#include<iostream>
#include<string>
#include<cstdlib>
#include<fstream>
using namespace std;
class Student
{
private:
int no;
string name;
double math;
double english;
double cpp;
double score;
public:
Student() {}
Student(int num,string n,double m,double e,double c,double s)
:no(num),name(n),math(m),english(e),cpp(c),score(s) {}
double getScore();
friend istream & operator >> (istream &in,Student &s);
friend ostream & operator << (ostream &out,Student &s);
};
double Student::getScore()
{
score=math+english+cpp;
return score;
}
istream & operator >> (istream &in,Student &s)
{
in>>s.no>>s.name>>s.math>>s.english>>s.cpp;
return in;
}
ostream & operator << (ostream &out,Student &s)
{
out<<s.no<<" "<<s.name<<" "<<s.math<<" "<<s.english<<" "<<s.cpp<<" "<<s.getScore()<<endl;
return out;
}
int main()
{
Student s[100],ss;
int i=0,no;
string name;
double math,english,cpp,score;
ifstream infile("D:\\score.dat",ios::in);
if(!infile)
{
cerr<<"Open Error!"<<endl;
exit(1);
}
while(!infile.eof())
infile>>s[i++];//读取ASCII文件
infile.close();
ofstream outfile("D:\\binary_score.dat",ios::binary);
if(!outfile)
{
cerr<<"Open Error!"<<endl;
exit(1);
}
outfile.write((char *)&s,sizeof(s));//以二进制写出
cin>>no>>name>>math>>english>>cpp>>score;
Student I(no,name,math,english,cpp,score);
outfile.write((char*)&I,sizeof(I));//末尾增加
outfile.close();
ifstream inFile("D:\\binary_score.dat",ios::binary);
if(!inFile)
{
cerr<<"Open Error!"<<endl;
exit(1);
}
while(true)
{
inFile.read((char *)&ss,sizeof(ss));//逐个读入验证
if(inFile.eof())
break;
cout<<ss;
}
inFile.close();
return 0;
}


运行结果:



心得体会:~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息