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

/*
*程序的版权和版本声明部分:
*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;
}


运行结果:

心得体会:~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值