关于c和c++中的eof函数多读一个问题

来源:互联网 发布:怀化学院教育网络系统 编辑:程序博客网 时间:2024/06/05 03:52

有不少人用eof函数碰到读多了一次的问题,但凡c/c++里的eof函数,比如feof,fstream对象的eof函数等等,都是相同的原理。

还原一下现场:

#include<iostream>#include<fstream>using namespace std;int main(){fstream out;out.open("test.txt",ios::out);int k=3;for(int i=0;i<6;i++)out<<k<<" ";out.close();out.open("test.txt",ios::in);while(!out.eof()){out>>k;cout<<k<<endl;}out.close();return 0;}


运行会发现写了6个3进去,打开文件看也是6个3,但是读却读了7个出来。

这主要是eof标志延迟了。eof主要是根据eofbit来确定返回值的:

bool eof(){if(eofbit)return true;else return false;}

而eofbit是在读取中设置的,读取到最后一次时,eofbit仍然为false;到下一次读取失败后,它才更新eofbit为true,也就是说要犯一次错才知道。在这尝试读取中,读取失败,所以k还是上一次的值。

因此,一般都是直接把读取语句放在while循环里面。

#include<iostream>#include<fstream>using namespace std;int main(){fstream out;out.open("test.txt",ios::out);int k=3;for(int i=0;i<6;i++)out<<k<<" ";out.close();out.open("test.txt",ios::in);while(out>>k){cout<<k<<endl;}out.close();return 0;}

如果一定要用eof函数,那么就先读取一次。

#include<iostream>#include<fstream>using namespace std;int main(){fstream out;out.open("test.txt",ios::out);int k=3;for(int i=0;i<6;i++)out<<k<<" ";out.close();out.open("test.txt",ios::in);//hereout>>k;while(!out.eof()){out>>k;cout<<k<<endl;}out.close();return 0;}

c语言中的函数也是类似这样子。




原创粉丝点击