2016-10-03 57 views
-1

这是代码。 它给出如下所示的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 

不知道为什么会发生这种情况!

+1

[OT]不要使用'eof'作为循环条件:http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – NathanOliver

+0

然后什么使用 ?以及为什么fin.fails为真 – akitsme

+0

正确的方法是使用读取操作。 – NathanOliver

回答

0

还没有找到原因,因为我相信没有人愿意 但我想通了,读空格和文件未做fin.fails() = truefin.fails()是真实的。 只是用while(fin.get(ch))代替while(!fin.eof()),并删除出现在body中的fin.get(ch) - >这就是为什么我的输出在每次阅读时跳过一个字符的原因..这是我在评论中提到的。

+0

是的,我在评论中也提到了这个,但是你告诉我我错了。 :smh: –

+0

我没有那么说!我知道那是我的错,'fin >> ch'不管理白色空间尝试自己 – akitsme

+0

这是你第一次提到空格.... –

0

的问题如下:读取的最后一个字符的文件与get设置eofbit,所以在你的while条件调用fin.eof()还是你读里面的文件的最后一个字符后false循环体。然后在读取最后一个字符后的迭代过程中,尝试读取循环体内的另一个字符,即使没有可读的字符。这将设置eofbitfailbit根据specificationget

TL; DR:读取文件末尾应设置为failbit

相关问题