我设计了一个基于链接列表的 BookStore,其中书籍的属性将存储在节点等中。另外,在程序结束时,我必须将所有数据库保存到文本文件中(我尝试过二进制读取,但该死的我被杀了并且无法做到)然后重新加载每本书的所有信息并将其存储在节点并重新制作链接列表。现在保存已完成,完全没有问题。但我在读取文本文件时遇到问题。
在文件中保存结构是:::
BookID(int) - BookName(string) - Author(string) - BookType(string) - Copies(long) - Price(long) - '\n'(转到下一行)
示例: 1 ObjectOrientedParadigm R.Lafore Coding 5 900 2 ObjectOrientedParadigm R.Lafore Coding 5 900 等等......
这里是保存功能。
bool BookStoreDataBase<mytype>::save_all_data()
{
if(!is_Empty()) //if list is not empty
{
BOOK<mytype> *temp = head; //created a copy of head
ofstream file("database.txt", ios_base::app); //created file, to write at the end (append)
while(temp != tail) //while list ends
{
file<<temp->ID<<' '<<temp->bookName<<' '<<temp->author<<' '<<temp->book_type<<' '<<temp->copies<<' '<<temp->price<<' '; //write all info
temp = temp->next; //move temp to next node
}
file<<temp->ID<<' '<<temp->bookName<<' '<<temp->author<<' '<<temp->book_type<<' '<<temp->copies<<' '<<temp->price<<' '; //for last book's info
return true; //to confirm sucessfull writing
}
else //if list is empty
{
return false; //to confirm error in writing
}
}
问题:: 当我开始阅读时,第一行被读取并存储在列表中,但是下一次,我不能让文件从下一行读取,因此是'\n'。&这会产生问题。文件再次读取第一行并使用相同的数据创建第二个节点。
加载功能:
void BookStoreDataBase<mytype>::load_all_data()
{
int ID; //variable to store ID of a book
string bookName;//string to store name of a book
string author; //string to store name of author of book
string book_type;//string to store type of a book
long copies; //variable to store no. of copies a book
long price; //variable to store price of a book
string status; //to store status of a book, either its in stock or not
ifstream file("database.txt");
while(file) //I have tried file.eof but its not working, don't know why
{
file>>ID>>bookName>>author>>book_type>>copies>>price>>status; //read file
BOOK<mytype> *temp = new BOOK<mytype>(0, 0, bookName, author, book_type, copies, price); //create a new node in memory and save all the data
if(is_Empty()) //if list is empty, then make 1st node
{
head = tail = temp;
}
else //other wise make the next node
{
tail->next = temp;
temp->prev = tail;
tail = temp;
}
}
}
MOREOVER 读数比实际记录少 1 倍。即如果 .txt 有 4 本书的记录,则创建 3 个节点,(每个节点中仅重复第 1 个的信息),而它应该读取并创建 4 个节点!
我是初学者,任何好的帮助将不胜感激。