【问题标题】:istream overloading -reading string from fileistream 重载 - 从文件中读取字符串
【发布时间】:2024-04-27 07:05:02
【问题描述】:

我正在尝试从文件中读取 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&);
};

【问题讨论】:

  • 抱歉无法得到您的问题 - 我没有写入文件..我能够从文件中读取一行并尝试将其作为对象的输入进行管道传输..
  • @Zeta:你能详细说明我如何使用 istringstream 来解决问题
  • std::istringstream ss(str); ss &gt;&gt; people;
  • 感谢您的回复..是的..

标签: c++ operator-overloading istream


【解决方案1】:

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

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

std::istringstream in(str);

in >> people;

【讨论】:

  • @oneday:我注意到你还没有接受任何答案。请参阅 this post on meta 以了解其工作原理。
最近更新 更多