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

本文介绍了一个简单的学生信息管理系统的设计与实现,该系统使用C++编程语言,通过文本文件和二进制文件来存储和读取学生的成绩信息。文章详细展示了如何定义学生类、实现输入输出操作符重载以及文件读写的流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/* 
*Copyright(c)2014,烟台大学计算机学院 
 *All rights reserved. 
 *文件名称:test.cpp 
*作者:曾晓 
 *完成日期:2015年 6月 2日 
 *版本号:v1.0 
   */  

#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(){};
    Student(int n, string nam, double c, double m, double e):num(n),name(nam),cpp(c),math(m),english(e){total=c+m+e;}
    void set_value(int n,string nam, double c, double m, double e);
    string get_name(){return name;}
    double get_cpp(){return cpp;}
    double get_math(){return math;}
    double get_english(){return english;}
    double get_total(){return total;}
    void set_cpp(double c){cpp=c;}
    void set_math(double m){math=m;}
    void set_english(double e){english=e;}
    void set_total(double t){total=t;}
    friend  ostream& operator<<(ostream&, Student&);
};
void Student::set_value(int n,string nam,double c,double m,double e)
{
    num=n;
    name=m;
    cpp=c;
    math=m;
    english=e;
}
ostream &operator <<(ostream &out,Student &s)
{
    out<<s.num<<" "<<s.name<<" "<<s.cpp<<" "<<s.english<<" "<<s.math<<" "<<s.total;
    return out;
}
int main()
{
    Student stud[100];
    int i,n;
    string sname;
    double smath,senglish,scpp;
      ifstream infile("score.dat",ios::in);  //以输入的方式打开文件,ASCII文件
    if(!infile)       //测试是否成功打开
    {
        cerr<<"open error!"<<endl;
        exit(1);
    }
    for(i=0;i<100;i++)
    {
        infile>>n>>sname>>scpp>>smath>>senglish;
        stud[i].set_value(n,sname, scpp, smath, senglish);
    }
    infile.close();

    //(三)将所有数据保存到一个二进制文件binary_score.dat中
    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 me(n,sname, scpp, smath, senglish);
    outfile.write((char*)&me, sizeof(me));
    outfile.close();

    //(四)为验证输出文件正确,再将binary_score.dat中的记录逐一读出到学生对象中并输出查看。
    Student s;
    ifstream infile2("binary_score.dat",ios::in|ios::binary);
    if(!infile2)
    {
        cerr<<"open error!"<<endl;
        exit(1);
    }
    while(true)
    {
        infile2.read((char*)&s, sizeof(s));
        if(infile2.eof()) break;
        cout<<s;
    }
    infile2.close();
    return 0;
}


 

没有好好看视频   搞得都 不会

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值