feof 作为循环判断条件的问题

>My program is reading the last line of data from an infile twice.
I'll bet my next paycheck that your file processing loop looks like this:

while ( !feof ( in ) ) {
  /* Read from the file and process */
}

Or this:

while ( !in.eof() ) {
  // Read from the file and process
}

The problem with that is feof (or stream.eof ) only returns true after an attempt has been made to read from the file and end-of-file was encountered. So your loop will iterate once more than you want, and because the input request failed you will use the last successfully read line. The result is that the last line of the file is processed twice.

The solution is to use the return value of your input function as the loop condition:

while ( fgets ( line, sizeof line, in ) != NULL ) {
  /* Process and print */
}

Or

while ( getline ( in, line ) ) {
  // Process and print
}

As an alternative, you can use an infinite loop and use feof or stream.eof in an if statement immediately after your input functions read from the file. That way you can break from the loop before processing the last line twice.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值