istream重载 - 从文件中读取字符串

时间:2014-12-05 07:31:13

标签: c++ operator-overloading istream

我正在尝试从文件中读取Person对象列表,将这些对象输出到内存中的流。如果我不必从文件中读取,我能够正常工作,我可以通过manaully输入每个对象值并且工作正常,但我正在努力将提取的行从文件作为输入传递给istream>>重载运算符

从文件中读取

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&);
};

1 个答案:

答案 0 :(得分:0)

假设你有一个字符串std::string str。您想在该字符串上使用格式化的提取。但是,std::string不是std::istream。毕竟,它只是一个简单的字符串。

相反,您需要一个istream,其内容与字符串相同。这可以通过std::istringstream

完成
std::istringstream in(str);

in >> people;
相关问题