我有一个对象矢量,其中包含很多变量(名称,类型,长度等),这些变量正试图写入文件。
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开始。第二个问题:您迭代“泊位”数组,因此,如果保存,则将获得N * N条船您在“泊位”中有N条船。
简单的解决方案是
如果必须将“ owner_name”,“ type”和其余字段设置为私有,则必须声明
并将'save_all'修改为
Every time
ofstream file("records_file.txt");
is called, it created a new file and overwrite it, if you want to append in the file you have to open it by this way:See: http://www.cplusplus.com/doc/tutorial/files/