Possible Duplicate:
Testing stream.good() or !stream.eof() reads last line twice
I’m working on an assignment where I am required to read data from a file into a linked list. So far I am able to read the file into the linked list with no problem, however everytime i read from the file into the list, i get one extra entry:
here’s my struct:
struct Video {
char video_name[1024]; // video name
int ranking; // Number of viewer hits
char url[1024]; // video URL
YouTubeVideo *next; // pointer to Video structure
} *head = NULL; // EMPTY linked list
here’s my read-in code:
void load()
{
ifstream rankFile ("Ranking.dbm");
struct Video *temp;
if (rankFile.is_open())
{
string line;
do {
temp = (Video*)malloc(sizeof(Video)); //allocate space for node
temp->next = head;
head = temp;
rankFile.getline(temp->video_name,1024);
rankFile >> temp->ranking;
getline(rankFile, line); // need to skip 'ranking's
// unread new-line
rankFile.getline(temp->url,1024);
}while (rankFile.good() );
rankFile.close();
}
else cout << "Unable to open file";
return ;
}
it is reading from a file that looks like this:
spiderman
100
spiderman.com
lucy
30
lucy.com
disney
1200
disney.com
these all read in fine, however it appears that the do-while(rankFile.good()); loop goes through one more iteration giving me an empty node in the linked list. I have already tried using all of my getline() statements as conditions of the while loop and that didnt seem to change anything. Also using rankFile != eof gave me no luck.
Is there a way to be checking the next I/O to make sure its not \n or the end of file?
Change it to
while(rankFile.good())instead of using thedo...whilesyntax.do...whiledoesn’t evaluate the terminating condition on your last iteration until after the contents of the loop have finished processing. A simplewhilewill evaluate before processing the loop body.