LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   using eof in c++ (https://www.linuxquestions.org/questions/programming-9/using-eof-in-c-679068/)

twelvenine 10-25-2008 09:20 PM

using eof in c++
 
i have to write some code that reads from a file until it reaches the end. it looks kind of like this:
Code:

ifstream input;
input.open(inputfile);
while(!input.eof())
{
input >> string;
cout << string << endl;
}

the file that it's reading from looks like this:
Code:

aaa
bbb
ccc
ddd

but for some reason, the above while loop will print out:
Code:

aaa
bbb
ccc
ddd
ddd

i can't figure out what's making it loop the extra time.

twelvenine 10-25-2008 10:21 PM

ok, i did some research and it seems that this is happening because of how the eof flag gets set. apparently it only gets set when you try to do a read, but nothing is there. so, i guess i could change the while loop to:
Code:

input >> string;
while(!input.eof())
{
cout << string;
input >> string;
}

but is there some way that i could update the eof flag without doing a read and throwing off the flow of my reads from the file? like say some function that i could call at the end of the while loop like input.updateeof().

paulsm4 10-25-2008 10:54 PM

Sure -

Code:

#include <stdio.h>
#define BUFLEN 80
...
  char buff[BUFLEN];
  while (fgets (buff, BUFLEN, fp))
    fputs (buff, fp);
  ...

;)

ta0kira 10-25-2008 11:30 PM

Quote:

Originally Posted by twelvenine (Post 3322000)
Code:

while(!input.eof())

It's better to use while (input) so that you also catch error states other than EOF.
ta0kira


All times are GMT -5. The time now is 07:44 AM.