使用输入文件流的eof()时要注意一个问题

从一个二进制数据文件courseFile.dat读取内容再将其输出到一个文本文件内。产生的文本文件的内容会多出一条,具体描述如下 :

二进制数据文件内容为两条记录,它们是(二进制格式无法精确表示出来):

0101  86  5
0102  72  4

但程序生成的courseFile.txt的内容第二条纪录会有重复,变成:

0101 86 5
0102 72 4

0102 72 4

显然,代码

while(!in.eof()){
in.read(reinterpret_cast<char *>(&theCourse),sizeof(course));
out<<setw(6)<<left<<theCourse.num<<setw(4)<<theCourse.hour<<setw(2)<<theCourse.credit<<endl;
}

比意想的多运行了一次out<<setw(6)......语句。 经过查资料知道,C++的read()函数刚刚读到文件尾时,eof()还是返回true.所以,while循环内的语句块多运行了一次。代码应改为:

while(1){
  in.read(reinterpret_cast<char *>(&theCourse),sizeof(course));
  if(!in.eof()){
   out<<setw(6)<<left<<theCourse.num<<setw(4)<<theCourse.hour<<setw(2)<<theCourse.credit<<endl;
  }
  else
   break;
 }

这样就输出正确的结果了。

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值