-1

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?

Community
  • 1
  • 1
accraze
  • 1,522
  • 7
  • 20
  • 46

2 Answers2

2

Change it to while(rankFile.good()) instead of using the do...while syntax. do...while doesn't evaluate the terminating condition on your last iteration until after the contents of the loop have finished processing. A simple while will evaluate before processing the loop body.

RJ Cuthbertson
  • 1,458
  • 1
  • 20
  • 36
0

Do-while loop executes first and checks the condition afterwards. So one step more always as first time, the loop would always run. While loop checks condition first before executing the body. So no extra iteration.

Check it here.

http://www.cplusplus.com/doc/tutorial/control/

Coding Mash
  • 3,338
  • 5
  • 24
  • 45