输出文件流产生双精度数

时间:2013-12-27 10:37:17

标签: 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(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();
}

我不知道双打来自哪里

1 个答案:

答案 0 :(得分:0)

您缺少MyObject ostream编写运算符:

std::ostream & operator<<(std::ostream & out, MyObject & o)
{
    out << o.filename .......
    return out;
}