这是代码。 它给出如下所示的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
不知道为什么会发生这种情况!
[OT]不要使用'eof'作为循环条件:http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – NathanOliver
然后什么使用 ?以及为什么fin.fails为真 – akitsme
正确的方法是使用读取操作。 – NathanOliver