我正在编写一个程序,需要从文本文件加载数据库。数据库类包含条目的 vector ,并且条目是一个类。
例
vector<People> lib;
class People {
string name;
string occupation;
int cats_age[2]
int age;
//code here
}
如何从包含已格式化条目的文本文件填充数据库
marry wang-dog walker-0-17-78
我尝试使用
file.read((char*)& entry, sizeof(entry))
但是没有用
我也考虑过重载运算符>>,但是某些字段是包含空格的字符串。
如何通过读取字符“-”之间的所有内容来填充对象?
-谢谢
最佳答案
您不能将文件中的原始read
转换为People
对象。 People
包含一个非平凡的类型(std::string
),文件中的每个记录必须具有相同的大小,才能进行原始读取,但文件中的情况并非如此。
人们通常要做的是为operator>>
添加一个重载,以支持来自任何std::istream
(例如std::ifstream
或std::cin
)的格式化输入。
由于成员变量是private
,因此您需要将添加的operator>>
设置为friend
,以便它可以访问private
变量。
您可以使用std::getline
进行读取,直到找到某个字符为止(例如分隔符-
)。它将从流中删除定界符,但不将其包括在存储结果的变量中。std::getline
返回对istream
的引用,该引用是从中读取的,因此您可以链接多个std::getline
。
我还将您的类(class)重命名为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
我建议您选择一个不同于
-
的字段分隔符。许多名称包含-
,负数也包含。使用不太可能包含在任何字段中的字符。
关于c++ - 从文本文件C++填充对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61136523/