Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

EOF problems

Status
Not open for further replies.

hedvule

Programmer
Oct 25, 2004
7
0
0
CH
Hi,

I have a text file that looks like this:
0 169 26
1 172 27
2 172 27
0 134 15
1 134 15
2 134 15
0 219 18

And I'm reading it with very simple loop

HitsIn.open(HitsFile);
while (!HitsIn.eof()) {
HitsIn >> DetectorNo >> Row >> Column;
// do something with these data
}

The problem is that the program reads the last line in the file always twice. I don't see any reason why it does this. Maybe I shouldn't use .eof(), but I don't know what to use instead. Could somebody help me please?

Thanks, Hedvika.
 
You are correct. You shouldn't use eof() like that because there is still a newline in the stream after the last line is read in so the eofbit is not set until you try to read one more line. When you tried to read another line and the line is empty, the read fails, but you are not checking for the success or failure of the read so you use the last line again.

To solve this, use the return value from the operator>> to control the loop:
Code:
while (HitsIn >> DetectorNo >> Row >> Column) {
// do something with these data
}
 
Thank you very much!! It was exactelly what I needed.
 
Also, reading ints as ints is generally a bad idea -- you probably want to read them as char and then use atoi to get the int values. The reason for this is if something happens and a letter is encountered then you test the data for that condition and handle the error properly as opposed to the program continuing to run with the filestream's/iostream's error flag set (often causing an infinate loop the next time you loop for input).

[plug=shameless]
[/plug]
 
While reading the data in as chars or a string is one way to handle it, it is not difficult to read in ints as ints and still handle the potential error of a char being there instead. Simply checking the return value of the operator>> call (which you should be doing anyway) and then clearing the stream flags and ignoring the leftover characters is easier in my opinion than reading in as chars and doing conversions.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top