第17周任务1(二进制文件的操作)

/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生 
* All rights reserved.
* 文件名称:                              
* 作    者:   臧鹏               
* 完成日期:   2012   年 6月 11 日
* 版 本 号:      001    

* 对任务及求解方法的描述部分
* 输入描述: 
* 问题描述: ASCLL文件score.dat中保存的是100名学生的姓名和C++课,英语课,高数课成绩。
1,定义学生类,其中包括姓名,C++课,高数课和英语成绩及总成绩,均分数据成员,成员函数根据需要确定。
2,读入学生的成绩,并求出总分,用对象数组进行储存。
3,将所有的数据保存到一个二进制文件binary_score.dat中,最后在文件中写入你自己的各科成绩
4,为验证输出的文件正确,再将binary_score.dat中的记录逐一读出到学生对象中并输出查看


* 程序输出: 
* 程序头部的注释结束
*/

#include<iostream>   
#include <fstream>   
#include<string>
using namespace std;  
class Student  
{
public:  
   Student(void){}  
   Student(string nam, double c, double m, double e, double all, double avs):name(nam),cpp(c), math(m), english(e), total(all), averagescore(avs){total=c+m+e;}
   void show();  
  
   friend void cin_score(Student stud[]);  //此处使用友元函数的作用是为了后面对私有数据成员的操作简便,不必多次调用get和set函数了
  
   friend void out_score(Student stud[]);  
  
private:  
    string name;  
    double cpp;  
    double math;  
    double english;  
    double total;  //总分
    double averagescore;  //平均分
};  
  
void Student::show()  
{  
    cout << name << '\t' << cpp << '\t' << math << '\t' << english << '\t' <<total<< '\t' << averagescore << endl;   
}  
  
void cin_score(Student stud[])  //进行读入操作
{  
    ifstream infile("score.dat",ios::in);    
  
    if(!infile)  
    {
		cerr<<"open score.dat error!"<<endl;  
        abort( );  
    }  
  
    for(int i = 0; i < 101; i++)  
    {      
        if(i == 100)  
        {  
            stud[i].name= "臧鹏";  
            stud[i].cpp = 100;  
            stud[i].math = 100;  
            stud[i].english = 100;  
        }  
  
        else  //并对其求总分和平均值
        {  
            infile >> stud[i].name >> stud[i].cpp >> stud[i].math >> stud[i].english;  
        }  
  
        stud[i].total = stud[i].cpp + stud[i].math + stud[i].english;  
        stud[i].averagescore = stud[i].total / 3;  
    }  
    infile.close( );  
}  
  
void out_score(Student stud[])  //读出操作
{  
    ofstream outfile("binary_score.dat",ios::binary);  
  
    if(!outfile)  
    { 
		cerr<<"open binary_score.dat error!"<<endl;  
        abort( );  
    }  
  
    for(int i = 0; i < 101; ++ i)  
    {  
        outfile.write((char *) &stud[i], sizeof(stud[i]));  
        stud[i].show();  
    }  
  
    outfile.close( );  
}  
  
  
int main( )  
{     
    Student stud[101];  
      
    cin_score(stud);  
  
    out_score(stud);  
  
    system("pause");  
  
    return 0;  
}  


 

经验积累:

整个程序的思路不过是读入,进行数据操作,然后读出。所以用课本中的一个程序,主函数中建一个对象后一个cin_score一个out_score就行了,程序中对私有数据成员又多次的访问,所以用多个set和get函数不是很方便,所以这可以利用友元函数的特点,把函数建成友元的,可以简化程序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值