您不能将原始 read 从文件转换为 People 对象。 People 包含一个重要的类型 (std::string),文件中的每条记录都必须具有相同的大小才能使原始读取工作,而您的文件中并非如此。
人们经常做的是为operator>> 添加一个重载,以支持来自任何std::istream 的格式化输入(如std::ifstream 或std::cin)。
由于成员变量为private,您需要将添加的operator>> 设置为friend,以便它可以访问private 变量。
您可以使用std::getline 读取直到找到某个字符(例如您的分隔符-)。它将从流中删除分隔符,但不将其包含在存储结果的变量中。
std::getline 返回对 istream 的引用,以便您可以链接多个 std::getlines。
我还将您的课程重命名为 Person,因为它只包含一个人的信息。
例子:
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
class Person {
std::string name;
std::string occupation;
int cats_age[2];
int age;
friend std::istream& operator>>(std::istream&, Person&);
friend std::ostream& operator<<(std::ostream&, const Person&);
};
// read one Person from an istream
std::istream& operator>>(std::istream& is, Person& p) {
using std::getline;
char del; // for reading the delimiter '-'
std::string nl_eater; // for removing the newline after age
// chaining getline:s and >>:s
return getline(getline(getline(is, p.name, '-'), p.occupation, '-') >>
p.cats_age[0] >> del >> p.cats_age[1] >> del >> p.age, nl_eater);
}
// write one Person to an ostream
std::ostream& operator<<(std::ostream& os, const Person& p) {
return os << p.name << '-' << p.occupation << '-' << p.cats_age[0] << '-'
<< p.cats_age[1] << '-' << p.age << '\n';
}
int main() {
// example of an istream - it could just as well had been a std::ifstream
std::istringstream is(
"marry wang-dog walker-0-17-78\n"
"foo bar-unemployed-1-2-3\n"
);
std::vector<Person> people;
Person temp;
while(is >> temp) { // loop for as long as extraction of one Person succeeds
people.push_back(temp);
}
// print all the collected Persons
for(const Person& p : people) {
std::cout << p;
}
}
输出:
marry wang-dog walker-0-17-78
foo bar-unemployed-1-2-3
我建议您选择与- 不同的字段分隔符。许多名称包含-,负数也是如此。使用不太可能包含在任何字段中的字符。