1. 程式人生 > >第16周———用二進位制檔案處理學生成績

第16周———用二進位制檔案處理學生成績

程式碼:

/*
*Copyright (c) 2016, 煙臺大學計算機與控制工程學院
*All rights reserved.
*檔名稱:ycy.cpp;
*作    者:嶽成豔 2016年6月24號;
*版 本 號:vc++6.0;
*
*問題描述:用二進位制檔案處理學生成績。
*程式輸入:略;
*程式輸出:略;
*/
#include <fstream>
#include<iostream>
#include<cstring>
#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=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&);
private:
    int num;
    string name;
    double cpp;
    double math;
    double english;
    double total;
};

void Student::set_value(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 stud[100]; //stud[100]為儲存資料的物件陣列
    int i,n;
    string sname;
    double scpp, smath, senglish;

    //(二)讀入學生的成績,並求出總分,用物件陣列進行儲存。
    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;
}