eof

OK I'm making a simple program to make a shopping list.
I would like the program at start up to load the previous shopping list that was saved as a text file. The format is one line per entry which consists of the category or Isle, and the item description. Here's an example:

3 Dog Food
Produce Sweet Onions

I reading the first word, and then I want to read the rest of the line which may have more than one word... the problem is my code hangs... or goes into the old infinite loop. It doesn't see the end of file.
Here is my code, any help would be great. Thanks.


void
addItemsFromFile(vector<item> &shoppingListVector)
{
string word;
char buf[30];
if (fileExists("shoppinglist.txt"))
{
ifstream fileIn("shoppinglist.txt");


while(!fileIn.eof())

{
fileIn >> word;

currentItem.itemLocation = word; // category
fileIn.getline(buf,30);

currentItem.itemCategory = buf; // Description
if (!fileIn.eof()) shoppingListVector.push_back(currentItem);
if (fileIn.eof()) break;
}
sort(shoppingListVector.begin(),shoppingListVector.end(),compareItems);

fileIn.close();
}
}
Last edited on
don't loop on eof, loop on the reading operation.
while( fileIn>>word and fileIn.getline(buf,30) )

> It doesn't see the end of file.
If your file is in an invalid state (by instance, it does not open) you'll never set the eof() flag.
Last edited on
Thanks, I'll try that.
Greg
Funny debugging it... it skips over the while loop completely. And the file does exist.

void
addItemsFromFile(vector<item> &shoppingListVector)
{
string word;
char buf[30];

if (fileExists("shoppinglist.txt"))
{
ifstream fileIn("shoppinglist.txt");



while( fileIn>>word and fileIn.getline(buf,30) )


{
// fileIn >> word;

currentItem.itemLocation = word;

//fileIn.getline(buf,30);

currentItem.itemCategory = buf;
shoppingListVector.push_back(currentItem);

}

sort(shoppingListVector.begin(),shoppingListVector.end(),compareItems);

fileIn.close();
}
}
Last edited on
Topic archived. No new replies allowed.