我正在为学校创建图书馆系统管理之类的东西
我有这个功能
void Book::AddBook(int index, const string& title, const string& author, const string& publisher, int year)
{
Book::loadBooks();
if (index >= 0 && index < maxsize && books[index] == nullptr)
{
books[index] = new Book(index, title, author, publisher, year);
cout << "Book with index " << index << " has been added to the library." << endl;
}
else if (index < 0 || index >= maxsize)
{
cout << "Error: Book index " << index << " is out of range." << endl;
}
else
{
cout << "Error: Book with index " << index << " already exists in the library." << endl;
}
Book::saveBooks();
}
void Book::saveBooks()
{
ofstream output("Books.txt");
if(output.is_open())
{
for(int i = 0; i < maxsize; i++)
{
if(books[i] != nullptr)
{
output << books[i]->getIndex() << ',' << quoted(books[i]->getTitle()) << ',' << quoted(books[i]->getAuthor()) << ',' << quoted(books[i]->getPublisher()) << ',' << books[i]->getYear() << endl;
}
}
output.close();
}
}
void Book::loadBooks()
{
ifstream input("Books.txt");
if (input.is_open())
{
int bookindex, year;
string title, author, publisher;
char delimiter;
while (input >> bookindex >> delimiter >> quoted(title) >> delimiter >> quoted(author) >> delimiter >> quoted(publisher) >> delimiter >> year)
{
if (bookindex >= 0 && bookindex < maxsize)
{
books[bookindex] = new Book(bookindex, title, author, publisher, year);
}
}
input.close();
}
}
在我的 main.cpp 中,只有 3 次调用函数,仅此而已。
#include <iostream>
#include "classes.h"
#include "classes.cpp"
int main() {
Librarian l;
l.addBook(0, "The Great Gatsby", "F. Scott Fitzgerald", "Charles Scribner's Sons", 1925);
l.addBook(1, "To Kill a Mockingbird", "Harper Lee", "J. B. Lippincott & Co.", 1960);
l.addBook(2, "1984", "George Orwell", "Secker & Warburg", 1949);
}
无论何时执行,它只将第一次调用写入文件。如果您对原因有任何想法,请告诉我。
顺便说一句,这是我的析构函数。
Book::~Book()
{
for (int i = 0; i < maxsize; i++)
{
if (books[i] != this && books[i] != nullptr)
{
delete books[i];
books[i] = nullptr;
}
}
}
我试过重写加载函数,删除它,整个函数在我脑海里反复了大约 30 分钟,但还是想不出来。