c++ - 从文本文件C++填充对象

标签 c++ class object vector file-io

我正在编写一个程序,需要从文本文件加载数据库。数据库类包含条目的 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::ifstreamstd::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/

相关文章:

c++ - 区分模板类构造函数中的 1D 和 2D 容器 (SFINAE)

c# - 如何在 C# 中的类中正确隐藏帮助程序(内部)类

ios - 将自定义对象添加到 NSMutableArray

递归要求的 C++ 模板类

c++ - 确定客户端 Internet 连接(InternetGetConnectedState() 谎言)

c++ - 在 x64 平台上发布配置独立执行的无效配置参数

javascript - 除了所选的 child 之外,将类(class)应用于 child 的 parent - JQuery

C++:指向包含子类的类的父指针

javascript - 在 jQuery 中将对象传递给 .attr()

arrays - 如何快速将 json 附加到我的数组