您的位置:首页 > 其它

用二进制文件处理学生成绩

2015-08-19 14:57 344 查看
输入代码:

<pre name="code" class="cpp">/*
* Copyright (c) 2014, 烟台大学计算机学院
* All rights reserved.
* 文件名称:sum123.cpp
* 作 者:林海云
* 完成日期:2015年8月19日
* 版 本 号:v2.0
*
* 问题描述:(1)定义学生类,其中包含学号、姓名、C++课、高数和英语成绩及
总分数据成员,成员函数根据需要确定。
(2)读入学生的成绩,并求出总分,用对象数组进行存储。ASCII文件score.dat中
保存的是100名学生的学号、姓名和C++课、高数和英语成绩。
(3)将所有数据保存到一个二进制文件binary_score.dat中,最后通过键盘输入你
的信息,并写入到文件中(咱不谦虚,三科全100分,期末求好运)。
(4)为验证输出文件正确,再将binary_score.dat中的记录逐一读出到学生对象中
并输出查看。
(5)用BinaryViewer命令查看二进制文件文件
* 输入描述:输入你的信息,并存贮
* 程序输出:文本输出
*/
#include<fstream>
#include<iostream>
#include<string>
#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=cpp+math+english;
}
void set_score(int n, string nam, double c, double m, double e)
{
num=n;
name=nam;
cpp=c;
math=m;
english=e;
total=c+m+e;
}
friend ostream &operator<<(ostream& out, Student& s);
private:
int num;
string name;
double cpp;
double math;
double english;
double total;
};
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[101];
int i,n;
string nam;
double c,m,e;
ifstream infile("score.dat",ios::in) ;
if(!infile)
{
cerr<<"open error!"<<endl;
exit(1);
}
for(i=0; i<100; i++)
{
infile>>n>>nam>>c>>m>>e;
stud[i].set_score(n,nam,c,m,e);
}
cout<<"文件读入完毕!"<<endl;
infile.close();
ofstream outfile("binary_score.dat",ios::out|ios::binary);
if(!outfile)
{
cerr<<"open error!"<<endl;
abort();
}
for(i=0; i<100; i++)
{
outfile.write((char *)&stud[i],sizeof(stud[i]));//1.outfile是某个已经打开的文件流;
//2.(char*)&stud[i] 取出stud数组第i个记录的地址并转换为char*类型指针
//3.sizeof(stud[i])获取记录的大小
//4.outfile.write(指针,大小)将指针所指区域指定大小的数据写入文件
//总之,这句代码的作用就是把stud中的第i个记录写入文件
}
cout<<"请输入你的信息:";
cin>>n>>nam>>c>>m>>e;
Student Lin(n,nam,c,m,e);
outfile.write((char*)&Lin, sizeof(Lin));
cout<<"数据存贮完成!"<<endl;
outfile.close();
Student s;
ifstream infile2("binary_score.dat",ios::binary|ios::in);
if(!infile2)
{
cerr<<"open error!"<<endl;
abort();
}
while (true)
{
infile2.read((char*)&s, sizeof(s));
if(infile2.eof()) break;
cout<<s;
}
infile2.close();
return 0;
}


运行结果:



score.dat



binary_score.dat



用BinaryViewer命令查看binary_score.dat的二进制文件:

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