c++ - C ++将对象向量写入文件
问题描述
我有一个包含很多变量(名称、类型、长度等)的对象向量,我正在尝试将其写入文件。
vector <Boat> berths;
void Boat::write_boats()
{
ofstream file("records_file.txt");
for (Boat b : berths)
{
file << owner_name << "; " << boat_name << "; " << type << "; " << length << "; " << draft << '\n';
}
file.close();
}
void save_records()
{
for (unsigned int i = 1; i < berths.size(); i++)
{
berths[i].write_boats();
}
}
我使用结束应用程序的菜单选项调用 save_records() 函数。
我得到的输出是:
1)如果我注册了一个船对象,关闭应用程序并进入文本文件,我可以看到该对象被写入了两次。
2)如果我注册 2 个对象并进入文本文件,则只有最后一个(第二个)对象已写入文件,并且显示 3 次。
现在我的问题是:
是什么导致双输出?
为什么只有最后一个对象写入文件?我认为循环会解决这个问题,但它没有
解决方案
我可以发现的一个问题:循环中的“i = 1”应该是“i = 0”,因为数组索引从 0 开始。第二个:你迭代 'berths' 数组,所以你将获得 N * N 艘船,如果您在“泊位”中有 N 艘船。
简单的解决方案是
void save_all()
{
ofstream file("records_file.txt");
for (Boat b : berths)
{
file << b.owner_name << "; " << b.boat_name << "; " << b.type << "; " << b.length << "; " << b.draft << '\n';
}
}
如果您必须将 'owner_name'、'type' 和其余字段设为私有,则必须声明
void Boat::save(std::ofstream& f) const
{
file << owner_name << "; " << boat_name << "; " << type << "; " << length << "; " << draft << '\n';
}
并将“save_all”修改为
void save_all()
{
ofstream file("records_file.txt");
for (const Boat& b: berths)
b.save(f);
}
推荐阅读
- c# - c#表单启动时放大图表
- python - 首次单线程运行相同的代码时,多处理不起作用
- android - kotlin 上 ProgressBar 后如何执行代码?
- flask - Flask - 无法从 API 调用返回响应
- c# - C#:将私钥从 XML 转换为 PEM 并将结果保存在文件中
- mysql - 全文搜索与索引检查完全相同的文本
- node.js - 如何创建文件并将其附加到电子邮件中?
- javascript - 将 HTML 脚本函数转换为 React JS
- javascript - 使用带有 react-fire 包的 firebase 模拟器
- python - Python Tkinter,无法将图像打开到画布