【发布时间】: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 >> people; -
感谢您的回复..是的..
标签: c++ operator-overloading istream