第15週項目1-学生成績をバイナリファイルで処理する

2734 ワード

(1)学号、氏名、C++課、高数および英語成績および合計スコアデータメンバーを含む学生クラスを定義し、メンバー関数は必要に応じて決定する.(2)学生の成績を読み込んで合計点を求め,対象配列で格納する.ASCIIファイルscore.datに保存されているのは100人の学生の学号、名前とC++授業、高数と英語の成績です.(3)すべてのデータをバイナリファイルbinary_に保存するscore.datでは、最後にキーボードであなたの情報を入力し、ファイルに書きます(謙虚ではありません.三科は100点で、期末は幸運を求めます).(4)出力ファイルが正しいことを確認するためbinary_score.datのレコードは、学生オブジェクトに1つずつ読み出され、表示が出力される.(5)BinaryViewerコマンドによるバイナリファイルファイルダウンロードの表示
#include <iostream>
#include <fstream>
#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),eng(e) {}
    friend  ostream& operator <<(ostream&, Student&);
    friend  istream& operator >>(istream&, Student&);
private:
    int num;
    string name;
    double cpp,math,eng;
    double sum;
};
ostream& operator<<(ostream &out, Student&s)
{
    out<<s.num<<'\t'<<s.name<<'\t'<<s.cpp<<'\t'<<s.math<<'\t'<<s.eng<<'\t'<<s.sum<<endl;
    return out;
}
istream& operator>>(istream &in, Student &s)
{
    in>>s.num>>s.name>>s.cpp>>s.math>>s.eng;
    s.sum=s.cpp+s.math+s.eng;
    return in;
}
int main()
{
    Student stu[100],my_s;
    ifstream infile("score.dat",ios::in);
    if(!infile)
    {
        cerr<<"open error!"<<endl;
        exit(1);
    }
    for(int i=0; i<100; ++i)
    {
        infile>>stu[i];
    }
    infile.close();
    ofstream outfile("binary.dat",ios::out|ios::binary);
    if(!outfile)
    {
        cerr<<"open error!"<<endl;
        exit(1);
    }
    for(int i=0; i<100; ++i)
    {
        outfile.write((char*)&stu[i],sizeof(stu[i]));
    }
    cout<<"      :"<<endl;
    cin>>my_s;
    outfile.write((char*)&my_s,sizeof(my_s));
    outfile.close();
    ifstream infile1("binary.dat",ios::in|ios::binary);
    if(!infile1)
    {
        cerr<<"open error!"<<endl;
        exit(1);
    }
    Student st;
    while(1)
    {
        infile1.read((char*)&st, sizeof(st));
        if(infile1.eof()) break;
        cout<<st;
    }
    infile1.close();
    return 0;
}
ピクチャ:
心得:
最後の出力では、次の構造を使用しました.
    while(!infile.eof())
    {
        infile1.read((char*)&st,sizeof(st));
        cout<<st;
    }
結果はプログラムの末尾に2回自分の成績が出るので、賀老のプログラムを参考にしてみましたが、先に読んでから判断すればファイルの末尾まで読み続けるのを防ぐことができるようですか?でも自分の成绩はもう书いてあるんだよね、ただ出力の判断方法が违うだけで、Soは実は分からない...