2

The text file contains lines formatted like so:

lSdhmhlN   15479   6694.74   O
szUfGnoI   18760   5275.53   n

I'm reading the file line by line, putting its data into buffer variables, storing those variables in a TopicD object, and inserting that object into a binary search tree. Problem is that the last line of the file is being read twice so that two identical TopicD objects are created and inserted into the tree. Why?

Here's my code:

template<class ItemType>
void read( BinarySearchTree<ItemType> & tree )
{
ifstream read( FILE_NAME.c_str() );

if ( read.fail() )
    die( "Error opening the file." );

string strbuff;
double dubbuff;
int intbuff;
char chbuff;

while ( !read.eof() )
{
    read >> strbuff;
    read >> intbuff;
    read >> dubbuff;
    read >> chbuff;
    TopicD buff( strbuff, dubbuff, intbuff, chbuff );
    tree.add(buff);
}

read.close();
}
JamesGold
  • 725
  • 1
  • 7
  • 23

1 Answers1

3

Consider snipping just a bit out of that loop:

while (read >> strbuff >> intbuff >> dubbuff >> chbuff)
    tree.add(TopicD( strbuff, dubbuff, intbuff, chbuff ));

Never rely on .eof() to be true when you reach EOF. Rather, it will be true when, among other things, you try to read again once you are there. Therefore your first read after arriving at EOF is failing, but by that time you've stopped checking for errors (which you were never checking to begin with, by the way) and just blindly insert whatever you have in your variables into your tree.

WhozCraig
  • 59,130
  • 9
  • 69
  • 128