PS glass PS glass - 1 year ago 94
C++ Question

Overload input stream operator>> for reading objects from file

I have a simple class

, which contains
and coordinates
. I have a text file, which looks like this:


Each line means following: The first in an indicator, that it is a city. Next is ID of city, name, size of population, x and y.

I want to read this file and creates a vector with cities. I know, that I need to overload an operator <<.

friend istream& operator >> (istream& is, City& c)
// I do not know

After that, I would be able to loads cities from a file in
loop. Can you help me please with overloading operator?

Answer Source

Like this:

#include <istream>
#include <sstream>

friend istream& operator >> (istream& is, City& c)
    // get whole line
    string line;
    if (!getline(is, line))
        // error reporting and exit goes here...

    // replace all ';' to ' '
    for (int i = 0; i < line.length(); i++)
        if (line[i] == ';')
            line[i] = ' ';

    // start parsing here
    istringstream iss(line);
    string tmp;
    if (iss >> tmp >> >> >> sizeOfPopulation >> c.x >> c.y)
        // error reporting and exit goes here...

    return input;

To read City objects in a loop, you can use:

City c;
while (is >> c) // suppose "is" is the opened input stream
    // successfully read a City, stored in c
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download