PS glass PS glass - 15 days ago 4
C++ Question

Overload input stream operator>> for reading objects from file

I have a simple class

City
, which contains
id
,
name
,
sizeOfPopulation
and coordinates
x
and
y
. I have a text file, which looks like this:

City;1;Stockholm;300000;45;78;
City;2;Helsinky;451200;11;74;
City;3;Prague;897455;12;85;


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
for
loop. Can you help me please with overloading operator?

Answer

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 >> c.id >> c.name >> 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
}