End of File in C++

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).

Leave a Comment