首页 > 解决方案 > 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 次。

现在我的问题是:

是什么导致双输出?

为什么只有最后一个对象写入文件?我认为循环会解决这个问题,但它没有

标签: c++objectvectorofstreamwritetofile

解决方案


我可以发现的一个问题:循环中的“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);
}

推荐阅读