Я пытаюсь ввести из файла, сохранить его в векторе, а затем вывести его снова в тот же файл. Но выход, похоже, вызывает удвоение, которое затем снова захватывается входом.
Вот мой код:
void MyClass::fill() { //MyClass has a vector<MyObject>
std::ifstream ifile("MyFile.ens");
std::string line, filename, title;
bool done;
int count;
// while(true) { }
// EDIT::USING WHILE(GETLINE...) INSTEAD OF WHILE(TRUE) FIXED IT FOR ME
while(getline(ifile, line)) {
if(ifile.eof()) {
break;
} else {
getline(ifile, line);
std::stringstream ss(line);
getline(ss, filename, ss.widen(';'));
getline(ss, title, ss.widen(';'));
ss >> done;
ss.get();
ss >> count;
MyObject obj(filename, title, done, count);
this->add(obj); //This does push_back on the vector
}
}
ifile.close();
}
Это работает так, как ожидалось. Но здесь вывод:
std::ostream& operator<<(std::ostream& out, MyClass& foo) {
std::vector<MyObject>::iterator it = foo.begin();
for (; it != foo.end(); ++it) {
out << *it << std::endl;
}
return out;
}
std::ostream& operator<<(std::ostream& out, const MyObject& bar) {
out << bar.filename_ << ";"
<< bar.title_ << ";"
<< bar.done_ << ";"
<< bar.count_;
return out;
}
void MyClass::save() {
std::ofstream ofile("MyFile.ens");
ofile << *this;
ofile.close();
}
Я не знаю, откуда взялись парни
У вас отсутствует оператор MyObject ostream writing:
std::ostream & operator<<(std::ostream & out, MyObject & o)
{
out << o.filename .......
return out;
}
MyClass::fill
вызывается только один раз? Я не вижу нигдеMyObject
спискаMyObject
, поэтому многократное заполнение приведет к дублированию.