Finding end of file while reading from it

后端 未结 5 1086
夕颜
夕颜 2021-01-16 06:09
void graph::fillTable()
{
  ifstream fin;
  char X;
  int slot=0;

  fin.open(\"data.txt\");

  while(fin.good()){

  fin>>Gtable[slot].Name;
  fin>>Gtab         


        
5条回答
  •  清歌不尽
    2021-01-16 06:37

    The file won't fail until you actually read from past the end of file. This won't occur until the fin>>Gtable[slot].Name; line. Since your check is before this, good can still return true.

    One solution would be to add additional checks for failure and break out of the loop if so.

    fin>>Gtable[slot].Name;
    fin>>Gtable[slot].Out;
    if(!fin) break;
    

    This still does not handle formatting errors in the input file very nicely; for that you should be reading line by line as mentioned in some of the other answers.

提交回复
热议问题