[英]istream overloading -reading string from file
我正在尝试从文件中读取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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.