家族族谱管理系统c++读写文件
时间: 2023-10-18 13:14:12 浏览: 48
为了实现家族族谱管理系统的读写文件功能,我们可以使用 C++ 的文件流操作。
首先,我们需要定义一个数据结构来表示家族成员和家族关系,比如:
```c++
struct Person {
string name; // 成员姓名
string gender; // 成员性别
int age; // 成员年龄
string spouse; // 配偶姓名(如果有)
vector<string> children; // 子女姓名(如果有)
};
```
然后,我们可以定义一个类来实现文件读写功能,比如:
```c++
class FamilyTree {
public:
void addPerson(Person person); // 添加一个成员
void removePerson(string name); // 删除指定姓名的成员
void print(); // 输出族谱
void save(string filename); // 保存族谱到文件
void load(string filename); // 从文件中加载族谱
private:
map<string, Person> people; // 用 map 存储所有成员信息
// 从字符串解析出一个 Person 对象
Person parsePerson(string line);
// 将一个 Person 对象转换成字符串
string formatPerson(Person person);
};
```
上面的代码中,我们使用了 STL 中的 `map` 来存储所有成员信息。`parsePerson` 和 `formatPerson` 函数分别用于将一个字符串解析成 `Person` 对象和将一个 `Person` 对象转换成字符串。
接下来,我们可以实现 `save` 和 `load` 函数:
```c++
void FamilyTree::save(string filename) {
ofstream outfile(filename);
if (!outfile.is_open()) {
cerr << "Error: cannot open file " << filename << endl;
return;
}
for (auto& p : people) {
outfile << formatPerson(p.second) << endl;
}
outfile.close();
}
void FamilyTree::load(string filename) {
ifstream infile(filename);
if (!infile.is_open()) {
cerr << "Error: cannot open file " << filename << endl;
return;
}
string line;
while (getline(infile, line)) {
Person person = parsePerson(line);
people[person.name] = person;
}
infile.close();
}
```
`save` 函数将所有成员信息写入到文件中,`load` 函数则从文件中读取所有成员信息并存储到 `people` 中。
最后,我们可以在 `main` 函数中测试一下:
```c++
int main() {
FamilyTree tree;
// 添加一些成员
tree.addPerson({"张三", "男", 30, "李四", {"王五", "赵六"}});
tree.addPerson({"李四", "女", 28, "张三", {"王五", "赵六"}});
tree.addPerson({"王五", "男", 5, "", {}});
tree.addPerson({"赵六", "女", 3, "", {}});
// 输出族谱
tree.print();
// 保存族谱到文件
tree.save("family.txt");
// 从文件中加载族谱
FamilyTree newTree;
newTree.load("family.txt");
newTree.print();
return 0;
}
```
运行程序后,你就可以看到族谱被保存到了 `family.txt` 文件中,并且从文件中加载出来后输出了出来。