首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

为什么最后一个人信息会读出两次?解决办法

2012-03-04 
为什么最后一个人信息会读出两次?#includeiostream#includefstream#include iomanipusingnamespaces

为什么最后一个人信息会读出两次?
#include   <iostream>
#include   <fstream>
#include <iomanip>
using   namespace   std;
struct   student
{
int   xueaho;
char   name[20];
};
void   writefile(   )
{  
student   stu;
fstream   ofs( "c:\\test.txt ",   ios::out|ios::binary);//定义fsteam对象,并打开文件
for(int   i=0;i <=2;i++)
{
        stu.xueaho   =9801+i;
        strcpy(stu.name   , "wanghai ");
ofs.write((char   *)&stu,sizeof(student));//写文件
}

ofs.close();
}
void   readfile()
{
student   stu;
        ifstream   tfile( "c:\\test.txt ",   ios::in|ios::binary);
        int   n=1;
   
        while(!tfile.eof())
{
  tfile.read   ((char   *)&stu,sizeof(student));
                  cout < <stu.xueaho < <stu.name < <endl;  
}

        tfile.close();
}

void   main()
{
        writefile(   );
        readfile();

}

[解决办法]
while(tfile.read ((char *)&stu,sizeof(student)), !tfile.eof())
{
cout < <stu.xueaho < <stu.name < <endl;
}
[解决办法]
while(!tfile.eof())
{
tfile.read ((char *)&stu,sizeof(student));
cout < <stu.xueaho < <stu.name < <endl;
}
以上代码就算tfile读到EOF,cout也会执行,因为读到EOF的原故,read的函数并不改变stu的内容,所以就变成最后的信息读了两次,可以改成这样:
tfile.read ((char *)&stu,sizeof(student));
while(!tfile.eof())
{
cout < <stu.xueaho < <stu.name < <endl;
tfile.read ((char *)&stu,sizeof(student));
}

[解决办法]
是因为
while(!tfile.eof())
{
tfile.read ((char *)&stu,sizeof(student));
cout < <stu.xueaho < <stu.name < <endl;
}

这种方式判断文件结束,
是通过出错标志进行的,
但是出错标志的设置,
是在错误发生之后。

所以,
在指向最后一条记录时候,
读取正确,指针后移;//这里读取了一次
继续读取,出错,设置标志 // 读取了第二此
再下次读取,发现 出错标志被设置, 结束循环。
这样导致多读取了一次。

这么修改:
tfile.read ((char *)&stu,sizeof(student));
while(!tfile.eof())
{
cout < <stu.xueaho < <stu.name < <endl;
tfile.read ((char *)&stu,sizeof(student));
}

即先读取,再判断,再输出,这样就可以了。

热点排行