您的位置:首页 > 其它

第15周上机实践项目1——用二进制文件处理学生成绩

2015-06-18 20:45 429 查看
(1)定义学生类,其中包含学号、姓名、C++课、高数和英语成绩及总分数据成员,成员函数根据需要确定。

(2)读入学生的成绩,并求出总分,用对象数组进行存储。ASCII文件score.dat中保存的是100名学生的学号、姓名和C++课、高数和英语成绩。

(3)将所有数据保存到一个二进制文件binary_score.dat中,最后通过键盘输入你的信息,并写入到文件中(咱不谦虚,三科全100分,期末求好运)。

(4)为验证输出文件正确,再将binary_score.dat中的记录逐一读出到学生对象中并输出查看。

代码

#include<iostream>
#include<fstream>
#include<cstdlib>
#include<cstring>
using namespace std;
class Student
{
public:
    Student(){};
    friend ostream &operator<<(ostream &out,Student &s);
    friend istream &operator>>(istream &in,Student &s);
private:
    int number;
    string name;
    double cpp,math,english;
};
ostream &operator<<(ostream &out,Student &s)
{
    out<<s.number<<"\t"<<s.name<<"\t"<<s.cpp<<"\t"<<s.math<<"\t"<<s.english;
    return out;
}
istream &operator>>(istream &in,Student &s)
{
    in>>s.number>>s.name>>s.cpp>>s.math>>s.english;
    return in;
}
int main()
{
    ifstream infile;
    infile.open("score.dat",ios::in);
    if(!infile)
    {
        cout<<"open,error!";
        exit(1);
    }
    Student s[101];
    int i=0;
    while(!infile.eof())
    {
        infile>>s[i];
        i++;
    }
    infile.close();
    ofstream outfile("binary_score.dat",ios::out|ios::binary);
    if(!outfile)
    {
        cout<<"open,error!";
        exit(1);
    }
    for(i=0;i<100;i++)
    {
        outfile.write((char*)&s[i], sizeof(s[i]));
    }
    cin>>s[i];
    outfile.close();
    fstream infile2("binary_score.dat",ios::out|ios::binary);
    Student a;
    while(!infile2.eof())
    {
        infile2.read((char*)&a, sizeof(a));
        if(infile2.eof()) break;
        cout<<a;
    }
    infile2.close();
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: