這是代碼。 它給出如下所示的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