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

istream overloading -reading string from file

本文关键字:读取 字符串 文件 重载 iStream      更新时间:2023-10-16

我正在尝试从文件中读取Person对象列表,将这些对象输出到内存流中。如果我不必从文件中读取,我能够让它工作,我可以手动输入每个对象值并且它工作正常,但我正在努力从文件中提取的行作为输入到 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&);
};

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

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

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