End of file in C ++

I have an n X 2 matrix stored in a text file as is. I am trying to read it in C ++

nb_try=0;
fin>>c_tmp>>gamma_tmp;
while (!fin.eof( ))      //if not at end of file, continue reading numbers
{
  // store
  cs_bit.push_back(c_tmp);
  gammas_bit.push_back(gamma_tmp);
  nb_try++;

  // read
  fin>>c_tmp;
  assert(!fin.fail( )); // fail at the nb_try=n   
  if(fin.eof( ))break;
  fin>>gamma_tmp; // get first number from the file (priming the input statement)
  assert(!fin.fail( ));    

}

The first statement does not hold, i.e. fin.fail () is true when nb_try == n, which happens when it tries to read the first number that does not exist. But how is it that fin.eof () is not true after reading the last number? Does this mean that it only becomes true when reading the first number that exists? Is it also true that fin.fail () and fin.eof () become true at the same time?

Thank you and welcome!

+3
source share
3 answers

This is the wrong way to read a file:

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

Standard template:

while(getlineOrValues)
{
    // Do Stuff
}

, , , :

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++;   
} 

, EOF , . , , EOF, . , , , EOF - , . c_tmp, EOF , .

, while. . (, while), , bool ( void *, ).

+13

IIRC, eofbit , . , , , .

+4

, , "12345 67890", # 3 false, # 4 true, :

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 return false, but # 5 and # 6 will return true.

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

0
source

Source: https://habr.com/ru/post/1718843/


All Articles