0

I wondered can I overload operator>> in a way that it can work for user input and from reading file. When I need input from user std::cin>>CCity1; and when I need from file std::ifstream ifstream(filename, std::ios::app); and then ifstream>>CCity1;

class CPerson {
    std::string m_strName;
    std::string m_strEGN;
    
    friend std::istream& operator>>(std::istream& is, CPerson& p) {
        is >> p.m_strEGN >> p.m_strName;
        return is;
    }
};

class CCity {
    std::string city;
    std::vector<CPerson>people;

    friend std::istream& operator>>(std::istream& is, CCity& p) {
        is >> p.city;
        CPerson temp("Empty", "Empty");
        while (std::cin) {
            is >> temp;
            p.people.push_back(temp);
        }
        return is;
    }
Belin
  • 33
  • 4
  • no this is not an endless loop. What does actually happen when you run this code and provide input via stdin? – 463035818_is_not_an_ai Nov 30 '20 at 17:53
  • 1
    That should be `while (is >> temp) {...}`, not `while (is) { is >> temp; ...}`. See [this question](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Kevin Nov 30 '20 at 17:57
  • Please, first extract a [mcve] that everyone here can easily reproduce. As a new user, also take the [tour] and read [ask]. – Ulrich Eckhardt Nov 30 '20 at 17:58

1 Answers1

0

You should use a container for the cities:

std::vector<CCity> city_database;
int main()
{
    CCity c;
    while (std::cin >> c)
    {
        city_database.push_back(c);
    }
    //...
    return 0;
}

The above code uses std::vector for the container. You may want to use another container depending on your needs.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154