File Input reads last line twice

Ok so I have a file that contains one-double-per-line entries & I know how many lines I have from another executable that creates & fills the file. Then I have as an example some code that goes like

#include <iostream>
#include <fstream>
using namespace std;

int main() {
double invar; //variable to store input from file
ifstream infile("...") //ellipsis denotes any good file w/ path, can depend
if(infile) {
while(!infile.eof()) {
infile >> invar;
cout << invar << '\n';
}
}
infile.close();
return 0;
}

So, when I run this code I see the last line of the file twice, and every other line once. Anyone know what would cause this? As a last resort, if I can't just use the extraction operator I will just use standard random access & keep track of the length of the file inside this code. However I would like to just use the simple interface. Thanks in advance.
edit: the formatting gets screwed when I post , no flaming please.
Last edited on
You have to test for eof after reading.

infile.eof() only returns true after you "read" EOF.

Reading the last line or last byte of a file is not EOF.
@ jsmith

Ok thanks that's what I was thinking; I had thought that for a read operation the current location in the file was the position of the next place to be read from, so I assumed that eof() would be true right after the last non-EOF read. I wonder why extraction returns the element of the previous extraction though; that's a little puzzling.

Oh and thanks for the quick response.
try
1
2
3
while(infile>>invar)
     cout<<invar<<"\n";
 

instead
Yes, yes, thank you.

Don't test on EOF.

It will cause you endless grief. Instead, test against istream::good() (as exampled for you by johnkravetzki).
Alright thanks for all the help. So istream::good() is called whenever an operation is performed on a stream?
No, it is just a shortcut.

When you say
if (infile)
that is (basically) the same as
if (infile.good())
-- it just has that nice C flavor to it that looks pretty.

The streams << operators return the stream, so
while (infile >> invar)
is (basically) the same as
while ((infile >> invar).good())

Hope this helps.
Alright gotcha. Another nice shortcut. After using the suggestions the program runs nicely. Thanks again for all the help.
Topic archived. No new replies allowed.