End of File in C++

前端 未结 3 764
再見小時候
再見小時候 2020-11-27 07:45

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

nb_try=0;
fin>>c_tmp>>gamma_tmp;
while (!fin.eof( ))      //if not          


        
3条回答
  •  轮回少年
    2020-11-27 08:15

    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.

提交回复
热议问题