Sandy
Sandy

Reputation: 41

fstream not reading all integers

I created a doubly linked list class and driver. I'm supposed to read in integers to the list from a text file but it's not reading the last number (37) and I'm not sure why. I'm almost positive it's not an issue with the initializeItem() or insertItem() functions so I'm not listing those but I can if needed.

Here's the text file:

9 10 3 84 19 63 1 45 100 37

Here's the code I have to read it in:

DoublyLinkedList list;
ItemType item;
int input;
std::fstream fs;

fs.open(argv[1], fstream::in);
if (fs.is_open())
{
    fs >> input;
    while (!fs.eof())
    {
        item.initialize(input);
        list.insertItem(item);
        fs >> input;
    }
}
else
{
    cout << "File could not be opened."
         << " Try again"
         << endl;
    return 0;
}

When I print out the list (sorted) I get this:

1 3 9 10 19 45 63 84 100

Upvotes: 0

Views: 208

Answers (1)

templatetypedef
templatetypedef

Reputation: 373052

The .eof() function on a stream doesn't trigger if an operation failed to complete due to reading the end of a file. Rather, it reports whether, in the course of any operation, it encountered the end of a stream. It's entirely possible that .eof() returns true even if the last operation succeeded. In fact, the general wisdom is that it is almost always wrong to test for .eof() if you're doing stream reads.

Here's a better way to read from the stream:

while (fs >> input) {
    ... do something with fs ...
}

This code will repeatedly pull values out of the stream until an operation fails to complete successfully (as determined by .fail(), not .eof()). This general pattern is probably the best way to read numbers from a stream if you know that they're whitespace-delimited.

Upvotes: 2

Related Questions