Search code examples
c++operator-overloadingistream

istream overloading -reading string from file


I am trying to read a list of Person objects from a file, outputs those objects to an in-memory stream. I am able to get it working if I dont have to read from a file, I can manaully enter each object value and its working fine, but I am struggling to pipe the extracted line from file as input to istream >> overloading operator

Reads from a file

string str
while (getline(inFile, str))
   {
     cout << "line" << str << endl; // I am getting each line
     cin >> people // if I manually enter each parameter of object it works fine
     str >> people // ?? - doesnt work - how do i pipe??
   }

Person.cpp
// operator overloading for in operator
istream& operator>> (istream &in, People &y)
{

    in >> y.firstName;
    in >> y.lastName;
    in >> y.ageYears;
    in >> y.heightInches;
    in >> y.weightPounds;
    return in;
}

class People
{
  string firstName;
  string lastName;
  int ageYears;
  double heightInches;
  double weightPounds;

   // stream operator
  friend ostream& operator<< (ostream &out, People&);
  friend istream& operator>> (istream &in, People&);
};

Solution

  • Lets say you have a string std::string str. You want to use formatted extractions on that string. However, std::string isn't a std::istream. After all, it's just a simple string.

    Instead, you need an istream with the same contents as the string. This can be done with std::istringstream:

    std::istringstream in(str);
    
    in >> people;