End of File in C++

佐手、 提交于 2019-11-26 19:09:38

This is the wrong way to read a file:

while (!fin.eof( ))
{
      // readLine;
      // Do Stuff
}

The standard pattern is:

while(getlineOrValues)
{
    // Do Stuff
}

So looking at your code quickly I think it would be asier to write it as:

while(fin>>c_tmp>>gamma_tmp)
{
    // loop only eneterd if both c_tmp AND gamma_tmp
    // can be retrieved from the file.

    cs_bit.push_back(c_tmp);
    gammas_bit.push_back(gamma_tmp);
    nb_try++;   
} 

The problem is that EOF is only true AFTER you try and read past it. Having no character left in the file to read is not the same as EOF being true. So you read the last line and get values and there is nothing left to read, but EOF is still false so the code re-enter the loop. When it tries and read the c_tmp then EOF gets triggered and your asserts go pear shaped.

The solution is to put the read as the while condition. The result of doing the read is the stream. But when a stream is used in a boolean context (such as a while condition) it is converted into a type that can be used as like a bool (Technically it is a void* but thats not important).

IIRC, the eofbit doesn't get set until you actually try to read past the end of the file. That is, once you reach the end of the file, you have to read one more time before that flag will be set.

If the text file contains this sequence, without quotes, "12345 67890", then #3 will return false, but #4 will return true because there is no whitespace after the last number:

int i;
bool b;

fin >> i;

b = fin.fail();  // 1
b = fin.eof();   // 2

fin >> i;

b = fin.fail();  // 3
b = fin.eof();   // 4

fin >> i;

b = fin.fail();  // 5
b = fin.eof();   // 6

However, if the sequence is "12345 6789 " (note the space after the last number), then #3 and #4 will both return false, but #5 and #6 will return true.

You should check for both, eof() and fail() and if both are true, you have no more data. If fail() is true, but eof() is false, there's a problem with the file.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!