/*
*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();
}
结果: