Search code examples
c++fstreamgetline

Having trouble reading items from a file (C++)


So, I'm having trouble getting the last item in a text file to read in to a string object.

I've created a class called "Car," and I'm supposed to have all of the parameters for a "Car" object read in from a file, but it won't register the last one.

The ifstream object is "data"

The variables are:

string carType;
string reportingMark;
int carNumber;
string kind;
bool loaded;
string destination;

The line in the text file reads as:

Car CN 819481 maintenance false NONE

This is what I have right now:

getline(data, ignore); // ignores the header line
data >> carType >> reportingMark >> carNumber >> kind >> loaded;
while (data.peek() == ' ') // this and the next lines were the suggestions of the teacher to bypass the spaces (of which there are more than it will display here)
   data.get();
getline(data, destination);

So, it will read everything in except for the "destination" part.


Solution

  • The problem is this part:

    data >> carType >> reportingMark >> carNumber >> kind >> loaded;

    Here you try to reed a Boolean variable loaded from a stream. You wish that reading false would work, but it doesn't. It accepts 0 or 1 only.

    Instead, failing to read the Boolean variable will toggle the err bit of the stream, which makes reading everything else after that fail.

    To check that, if you do data.peek() right after that line you will receive a -1, indicating no valid input.

    To fix that you will need to either change you way of storing information to store 0/1 instead of true/false, or better yet:

    Do: data << boolalpha before reading the data. This will make the stream interpret true/false as 0/1.