Shane said:
I looked at that exact article before, but ignored it because it skips the
whole purpose of using getline for everything else. In other words, if my
record looks like this:
Item name with spaces
Record
Full Name with spaces
(e-mail address removed)
4.44
Available on request with spaces
then I have issues. So I tried your suggestion, but I lose the first cin in
the record to the x variable. This throws the whole record off. If I use
getline, I can grab everything in the line and pull it into the variable of
my choice. Am I missing something?
Thanks again for the help!
Yes, the example uses operator>>, but the idea can be applied to many other
circumstances as well. The problem is the same: eof() is being set after
you attempt to read past the end of the file. The first iteration does not
attempt to read _past_ the end of the file, so the loop continues on for
another iteration, adding a second object to the linked list. You do not
check to see if any of the input operations succeed, so the second iteration
silently fails to retrieve input from the file after the first iteration
read all of the input.
Now, suppose there were a function std::istream& operator>>(std::istream&,
Multimedia&) that would allow you to read a Multimedia from a stream. Then
you could write your loop as
Multimedia m;
while( Multi >> m ) {
MM.push_back(m);
}
if ( !Multi.eof() ) {
// Something bad happened. Should have attempted to read past
// the end of the file to end the loop.
}
The above would silently ignore a partial Multimedia entry, but you could
fix that, if you like. The other option would be to add error handling to
your code. For example,
getline(Multi, Item, '\n');
should be changed so you know if the read was successful, like so
if ( !getline(Multi, Item, '\n') ) {
std::cerr << "Error reading Item" << std::endl;
break;
}
You'll need to add similar error handling for the other input operations you
perform. Your code will now complain loudly when it fails to read from the
file. However, that would still render your call to eof() useless, because
the loop will most likely end once an error has occurred, not when eof()
returns true. Give those changes a shot and see if it helps you understand
what's going on.