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

/*
 *Copyright (c) 2014, 烟台大学计算机学院
 *All rights reserved.
 *文件名称:week15-1.cpp
 *作者:高赞
 *完成日期: 2015 年 6 月 15 日
 *版本号:v1.0
 *
 *
 */
#include <iostream>
#include <cstring>
#include <fstream>
#include <cstdlib>
using namespace std;
const int Num=100;
class student
{
private:
    string number;
    string name;
    double cpp;
    double math;
    double english;
    double total;
public:
    student () {}
    void getdata(string,string,double,double,double,double);
    void outdata();
};
void student::getdata(string num,string n,double c,double m,double e,double t)
{
    number=num;
    name=n;
    cpp=c;
    math=m;
    english=e;
    total=t;
}
void student::outdata()
{
    cout<<number<<" "<<name<<" "<<cpp<<" "<<math<<" "<<english<<" "<<total<<endl;
}
int main()
{
    student s[Num],my,S;
    string num,na;
    double c,m,e,t;
    int i;
    ifstream infile("score.dat",ios::in);
    if(!infile)
    {
        cerr<<"open error!"<<endl;
        exit(1);
    }
    for(i=0; i<Num; ++i)
    {
        infile>>num>>na>>c>>m>>e;
        t=c+m+e;
        s[i].getdata(num,na,c,m,e,t);
    }
    infile.close();
    ofstream outfile("binary_score.dat",ios::out|ios::binary);
    if(!outfile)
    {
        cerr<<"open error!"<<endl;
        exit(1);
    }
    for(i=0; i<Num; ++i)
    {
        outfile.write((char*)&s[i],sizeof(s[i]));
    }
    cout<<"输入信息:"<<endl;
    cin>>num>>na>>c>>m>>e;
    t=c+m+e;
    my.getdata(num,na,c,m,e,t);
    outfile.write((char*)&my,sizeof(my));
    outfile.close();
    ifstream in("binary_score.dat",ios::in|ios::binary);
    if(!in)
    {
        cerr<<"open error!"<<endl;
        exit(1);
    }
    while(!in.eof())
    {
        in.read((char*)&S,sizeof(S));
        S.outdata();
    }
    in.close();
    return 0;
}


然而,用上面的代码输出结果如下:


最后一行明显多输了一遍。

原因:第85行的while(Iin.eof())。

           因为in.eof()判断文件结束是通过读取函数read返回错误来识别的。

           当read刚好读到最后一行,此次循环eof()是判断不出到了文件尾的,但read变为false,所以就再一次循环,这次判断read返回false,故多输一遍。

解决办法: 改为如下

while(1)
    {
        in.read((char*)&S,sizeof(S));
        if(in.eof())break;
        S.outdata();
    }


结果:


  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值