简体   繁体   中英

Reading from input file C++ with istream operator overloading

I have an input file which I cannot change, with slightly differently lines

Supercar   HTT Technologies   10   2
Motorcycle   Honda   40   1
...

I have overloaded the >> operator in order to read in the values into my data structure, which is as follows:

class Vehicles{
private:
string type;  //type of vehicle, i.e. car/motorcycle
string manufacturer;
string manufacturer2ndPart //not a good idea, but this is what I'm using
                           //to get the second part of the manufacturer ("Technologies")
int milesPerGallon;
int numPrevOwn //number of previous owners
public:
...

friend istream &operator >> (istream &is, Vehicles &Vec){
 is >> Vec.type >> Vec.manufacturer >> Vec.milesPerGallon >> Vec.numPrevOwn;
 return is;
     }
};

This works fine for the first line, but breaks down on the second line of the input file, because it tries to read in "40" into manufacturer2, instead of milesPerGallon. What would be the best way to solve this problem? I want to avoid reading everything in manually as this defeats the purpose of my operator overload.

Your basic problem is that a stream's >> overloads all stop when they encounter whitespace, and your input file includes spaces as data rather than as something to ignore. Hence your problem with needing different number of strings depending on the line.

Generally speaking, you would be better off reading a whole line at once to a string (eg using std::getline() ). Then examine the string to work out how many fields it actually contains before trying to actually extract them. In other words, don't use streaming operators to read from the file (or write to it).

It might also pay to change the file format slightly so it make it obvious when the beginning of string fields are. For example, a format like

"Supercar"  "HTT Technologies"   10     2
"Motorcycle" "Honda"    40     1

You'll still need to read a line at a time, but using " to delimit strings makes it easier to recognise the beginning and each of each string, and deal with them containing whitespace (other than a newline). If you need to have a " character in the string, specify that it will be preceded by a \\ , and parse the input accordingly.

Obviously, any code to read or write such a file, will need to comply with the same protocol. And the reading code will need to deal with errors (eg a file that does not comply with the protocol).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM