C++ 输出文件流产生双精度
我试图从一个文件中输入,保存在一个向量中,然后再次输出到同一个文件中。但输出似乎会产生双倍,然后再由输入拾取 这是我的密码:C++ 输出文件流产生双精度,c++,vector,ifstream,ofstream,C++,Vector,Ifstream,Ofstream,我试图从一个文件中输入,保存在一个向量中,然后再次输出到同一个文件中。但输出似乎会产生双倍,然后再由输入拾取 这是我的密码: void MyClass::fill() { //MyClass has a vector<MyObject> std::ifstream ifile("MyFile.ens"); std::string line, filename, title; bool done; int count; // while(tru
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();
}
void MyClass::fill(){//MyClass有一个向量
std::ifstream ifile(“MyFile.ens”);
std::字符串行、文件名、标题;
布尔多;
整数计数;
//while(true){}
//编辑::使用WHILE(GETLINE…)而不是WHILE(TRUE)为我修复了它
while(getline(ifile,line)){
如果(ifile.eof()){
打破
}否则{
getline(ifile,line);
std::stringstream ss(线路);
getline(ss,filename,ss.gaveland(“;”);
getline(ss,title,ss.wilding(“;”);
ss>>完成;
ss.get();
ss>>计数;
MyObject对象(文件名、标题、完成、计数);
this->add(obj);//这会将_推回向量
}
}
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();
}
std::ostream&operator您缺少MyObject-ostream写入运算符:
std::ostream & operator<<(std::ostream & out, MyObject & o)
{
out << o.filename .......
return out;
}
std::ostream&operator@JN11包括它并让我们检查它。您确定只调用一次MyClass::fill
?我在任何地方都看不到MyObject
的清除列表,因此多次填充都会产生重复项。请向我们显示您文件的初始内容。