您的位置:首页 > 其它

第十五周 项目一:用二进制文件处理学生成绩

2015-06-14 20:41 483 查看
问题及代码:

/*
* Copyright (c) 2015, 烟台大学计算机学院
* All rights reserved.
* 文件名称:Project4.cpp
* 作    者:李楠
* 完成日期:2015年6月14日
* 版 本 号: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);
int getnum()
{
return num;
}
string getname()
{
return name;
}
double getcpp()
{
return cpp;
}
double getmath()
{
return math;
}
double getenglish()
{
return english;
}
double gettotal()
{
return total;
}
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.txt",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;
}


运行结果:





知识点总结:

最开始没注意学号的长度用了int,后来又换了一下才输出正确。

因为成员函数写得比较简单所以main函数写得比较多,还有待改进。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: