3

So I am reading in data from a text file in to a vector using a while loop.

Originally I had the code set up this way :

iftream infile;
while(infile)  // or even if i do while(!infile.eof())
    {
        infile>>data;
        vector1.push_back(data); //adding data in to the vector
    }

- but this caused one small problem that it read in the last item in the text file twice for some reason.

but if I have the code set up this way everything works fine :

iftream infile;
while(infile>>data)
{
    vector1.push_back(data); //adding data in to the vector
}

Why does the first code reads in the last item twice?

psj01
  • 2,441
  • 3
  • 22
  • 52
  • 1
    It doesn't read the last item twice. Rather, you ignore the fact that the *very last read* **failed**, then blindly inserts the read from the last successful iteration. By testing the success of the extraction as the condition of the loop, you avoid that problem. in short, validate your extractions before using them (which you second snippet does and the first snippet does *not*). – WhozCraig Apr 06 '14 at 20:03
  • @WhozCraig even with the first snippet.. it should skip the while loop when it sees that there is nothing to read in , right? while (!infile.eof()) means that it will only do the loop as long as its not the end of the file right.. but once its end of file it should skip the loop right?.. – psj01 Apr 06 '14 at 20:26
  • Not quite. The linked duplicate is honestly the best description you're going to get for why you simply don't use eof or eof-logic in a loop control conditional. The expression `inifile` is synonymous with `!inifile.fail()` which will be true so long as neither the bad-bit nor fail-bit are set. Since neither have been set yet (you haven't tried to read *beyond* eof and no other failure has happened), the expression is still true. – WhozCraig Apr 06 '14 at 22:15

1 Answers1

3

It looks like your data structure is not entirely aligned within the file, i.e. when your program tries to read the last fragment, it hasn't reached the end of file yet, but there isn't enough data to read. So infile >> data fails, that means that the contents of data haven't been changed, and therefore you add it to your vector again.

In the second case, you check for the result of the read, therefore you don't attempt to push the data contents when it wasn't read properly.

Ashalynd
  • 11,728
  • 2
  • 29
  • 35
  • but how does it get inside the while loop since it should only go in to the loop if while(infile) is true.. If there is nothing to read in then it should skip the loop right?.. that was my logic.. – psj01 Apr 06 '14 at 20:23
  • I guess (that's the only thing I can do without seeing your data struct def and file contents) that it has not reached the end of file yet (e.g. there are a couple of spaces there or something like that), so it still tries to read the next data chunk and fails. – Ashalynd Apr 06 '14 at 20:31