[英]Why input stream object fails after reading file to the end?
这是代码。 它给出如下所示的 EXACT 输出意味着它正在读取文件。 但它也显示fails
如您所见,这意味着fin.fails()
为true
。 我想知道为什么这是真的,尽管我成功阅读了文件。
#include<fstream>
#include<iostream>
using namespace std;
int main()
{ ifstream fin;
fin.open("pro.txt");
char ch;
int data;
while(!fin.eof())//!(fin >> ch).eof()
{
fin.get(ch);
cout<<ch;
if(fin.fail()) {
cout<<"fails";
break;
}
}
fin.clear();
fin.seekg(0);
int pos=(int)fin.tellg();
cout<<"\n this is :"<<pos;
fin.close();
return 0;
}
Output is :
this is my name
fails
this is 0
Contents of pro.txt:
this is my name
不知道为什么会这样!
仍然无法找到为什么fin.fails()
是真的,因为我认为没有人愿意但我想在不使fin.fails()
= true
情况下读取空格和文件。 只需将while(!fin.eof())
替换为while(fin.get(ch))
并删除 while body 中的fin.get(ch)
-> 这就是我的输出为每个字符跳过一个字符的原因阅读..这是我在评论中提到的。
问题如下:使用get
读取文件中的最后一个字符不会设置eofbit
,因此在读取循环体中文件的最后一个字符后, while
条件中对fin.eof()
的调用仍然返回false
. 然后在读取最后一个字符后的迭代期间,您尝试读取循环体内的另一个字符,即使不再读取任何字符。 这将根据get
规范设置eofbit
和failbit
。
TL;DR:读取文件末尾应该设置failbit
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.