为什么c++中用while(file){ }在读取文件的时候总是会重复显示最后一条记录

ifstreaminfile("stu.dat",ios_base::in|ios_base::binary);cout<<endl<<"从stu文件读出为:"<<end... ifstream infile("stu.dat",ios_base::in|ios_base::binary);
cout<<endl<<"从stu文件读出为:"<<endl;
while(!infile.eof())
{
student stu_temp;
infile.read(reinterpret_cast<char *>(&stu_temp),sizeof(stu_temp));
cout<<"sno: "<<stu_temp.sno<<endl;
cout<<"sname: "<<stu_temp.sname<<endl;
cout<<"score: "<<stu_temp.score<<endl;
}
infile.close();
用上面这段代码读取文件中的内容的时候,最后一条记录总是重复被输出,哪位大虾帮忙看看是哪里的问题,无限感谢!
展开
 我来答
zdj1414
2010-12-19
知道答主
回答量:12
采纳率:0%
帮助的人:10.3万
展开全部
ifstream infile("stu.dat",ios_base::in|ios_base::binary);
cout<<endl<<"从stu文件读出为:"<<endl;
student stu_temp;
while(infile.read(reinterpret_cast<char *>(&stu_temp),sizeof(stu_temp)))
{
cout<<"sno: "<<stu_temp.sno<<endl;
cout<<"sname: "<<stu_temp.sname<<endl;
cout<<"score: "<<stu_temp.score<<endl;
}
infile.close();

如果读成功的话,infile.read会返回stu_temp的地址,否则返回NULL。
匿名用户
2010-12-19
展开全部
在while循环内部再加一次eof判断。
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式