您的位置:首页 > 其它

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

2015-06-15 19:07 459 查看
问题及代码:

/*   
*Copyright (c)2015,烟台大学计算机与控制工程学院   
*All rights reserved.   
*文件名称:File.cpp   
*作    者:单昕昕   
*完成日期:2015年6月15日   
*版 本 号:v1.0   
*问题描述:
(1)定义学生类,其中包含学号、姓名、C++课、高数和英语成绩及总分数据成员,成员函数根据需要确定。 
(2)读入学生的成绩,并求出总分,用对象数组进行存储。ASCII文件score.dat中保存的是100名学生的学号、姓名和C++课、高数和英语成绩。 
(3)将所有数据保存到一个二进制文件binary_score.dat中,最后通过键盘输入你的信息,并写入到文件中(咱不谦虚,三科全100分,期末求好运)。 
(4)为验证输出文件正确,再将binary_score.dat中的记录逐一读出到学生对象中并输出查看。 
(5)用BinaryViewer命令查看二进制文件文件 
*程序输入:个人信息。
*程序输出:所有人的信息。
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>//为了使用exit()
#include <fstream>
using namespace std;
//定义学生类
class Student
{
public:
    //声明必要的成员函数
    Student() {};
    friend istream& operator>>(istream &input, Student &s);
    friend ostream& operator<<(ostream &output, Student &s);
private:
    string name;
    long no;  //学号
    double cpp;
    double math;
    double english;
    double total;
};

istream& operator>>(istream &input,Student &s)
{
    input>>s.name>>s.cpp>>s.math>>s.english;
    s.total=s.cpp+s.math+s.english;
    return input;
}

ostream &operator<<(ostream &output,Student &s)
{
    output<<s.name<<'\t'<<s.cpp<<'\t'<<s.math<<'\t'<<s.english<<'\t'<<s.total;
    return output;
}

int main( )
{
    Student stud[101],t; //stud[101]为保存数据的对象数组,多出来的1是用来保存我自己的成绩的
    string sname;
    int i;
    //从文件score.dat中读入数据,保存到对象数组中
    ifstream infile("score.dat",ios::in);
    if(!infile)
    {
        cout<<"Can’t open the file."<<endl;
        abort();
    }
    ofstream outfile("binary_score.dat",ios::binary);
    if(!outfile)
    {
        cout<<"Can’t open the file."<<endl;
        abort();
    }
    cout<<"请输入你的信息:"<<endl;
    cin>>stud[100];
    for(i=0; i<101; ++i)
        outfile.write((char*)&stud[i],sizeof(stud[i]));
    infile.close();
    outfile.close();
    cout<<"The datas have been writen to file. "<<endl;
    return 0;
}


运行结果:



二进制文件阅读器。。



知识点总结:

用二进制文件处理学生成绩。

学习心得:

(⊙o⊙)…这个这个。。用阅读器也看不懂阿!!

怎!么!破!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: