I am trying to make a small menu-driven bookstore application where one is able to:
- Add Books
- Search for the books
- Display all the books
- Save the data to a .txt file
Everything was working fine until I decided to read data from any previously made file (and maybe put it to use so that the bookstore is not always empty in the beginning).
After I am done with all the operations, the objects are successfully written to a .txt file and it can also be read without any issue.
But I can't read it in the beginning (from an existing file).
Here is the class (similar to the full-fledged program) which I made.
class BookStore {
class Book {
string BookTitle;
int BookCost;
int BookStock;
public:
Book(){
};
~Book() {
};
Book(string title, int cost, int stock) {
BookTitle = title;
BookCost = cost;
BookStock = stock;
}
string getTitle(){
return BookTitle;
}
int getCost() {
return BookCost;
}
int getStock() {
return BookStock;
};
}; // inner class Book ended
public:
Book* bk[5] = { NULL };
void SaveToFile() {
fstream fop;
fop.open("Catalogue.txt", ios::out | ios::binary);
int lim = 3;
bk[0] = new Book("book1",40,3);
bk[1] = new Book("book2",50,3);
bk[2] = new Book("book3",60,3);
for (int i = 0; i < lim; i++)
fop.write((char*)&(*(bk[i])), sizeof(Book));
fop.close();
}
void RetrieveFromFile() {
fstream f;
f.open("Catalogue.txt", ios::binary | ios::in);
if (f.good() == 1) {
cout << "\n Existing file found... Reading data... \n";
f.seekg(0);
Book b;
f.read((char*)&b, sizeof(Book));
while (!f.eof())
{
cout << "\n ------- \n";
cout << "Book Title : - " << b.getTitle() << "\n";
cout << "Book Cost : - " << b.getCost() << "\n";
cout << "Available Stock : - " << b.getStock() << "\n";
f.read((char*)&b, sizeof(Book));
}
f.close();
}
else
cout << "\n Suitable Pre-existing File not found";
}
}; // end of class BookStore
There is no compile-time error. And the screen just freezes for a moment when it is trying to display data, and then shows the 'Press any key to continue...' statement.
I ran it in the debug mode and got:
Unhandled exception at 0x00007FFD118EC231 (ucrtbased.dll) in main_BookStore.exe: 0xC0000005: Access violation reading location 0x0000018B5FEFDCD0.
Here is the main()
int main() {
BookStore* bs = new BookStore();
bs->SaveToFile();
bs->RetrieveFromFile();
return 0;
}
So if I try to do
{
BookStore* bs = new BookStore();
bs->RetrieveFromFile();
return 0;
}
It doesn't go through successfully. I was expecting to see all the 3 book details.
Aucun commentaire:
Enregistrer un commentaire