文件I / O打印输出错误

时间:2018-07-08 12:50:49

标签: c++

我的代码工作正常,但是每当调用析构函数并将其打印回文件时,它都将打印出的内容比上一次间隔更大 enter image description here

    #include <fstream>
    #include "Catalog.hpp"
    #include "Book.hpp"
    void Catalog::AddBook(){
        Book tmp;
        string ISBN,Title;
        cin.ignore(1000,'\n');
        cout <<"Enter Book's Title to add to the List: "<<endl;
        getline(cin,Title);
        //check if the person already exists in the system
        if(findTitle(Title)){
            cout <<"This Book's Title already exists"<<endl;
        }
            else{
                cout << "Enter the ISBN to add to the list: "<<endl;
                cin >> ISBN;
                if(findISBN(ISBN)){
                    cout <<"This Book's ISBN already exists"<<endl;
                }else{
                    tmp.setISBN(ISBN);
                    tmp.setTitle(Title);
                    listofBooks.push_back(tmp);
                }
            }
        }

    Catalog::~Catalog(){
        ofstream f1(filename);
        if(f1.fail()){
            cout<<"Failed to open the file";
            exit(0);
        }
        for(int i=0;i<listofBooks.size();i++){
            f1 << listofBooks[i].getISBN() << " " << listofBooks[i].getTitle() << endl;
        }
        f1.close();
        f1.flush();
    }



Catalog::Catalog(string fileName){
    filename = fileName;
    ifstream f1(fileName);
    if(f1.fail()){
        cout<<"Failed to open the file";
        exit(0);
    }
    Book tmp;
    string ISBN,Title;
    f1 >> ISBN;
    getline(f1,Title);
    tmp.setISBN(ISBN);
    tmp.setTitle(Title);
    while(!f1.eof()){
        listofBooks.push_back(tmp);
        f1 >> ISBN;
        getline(f1,Title);
        tmp.setISBN(ISBN);
        tmp.setTitle(Title);
    }
    f1.close();
}

如果您需要更多信息,请提及它,该程序会在我将新书添加到列表中时添加更多的空格。

0 个答案:

没有答案