Book.h
#include <iostream>
#include <stdio.h>
using namespace std;
class Book {
public:
int Book_no;
char Book_name[20];
Book() {
}
void enterdetails() {
cout << "Enter No ";
cin >> Book_no;
cout << "Enter name ";
cin >> Book_name;
if (Book_no < 0) {
throw exception();
}
}
void showdetails() {
cout << Book_no << " - " << Book_name << endl;
}
// function to return Book_no
int Rbook_no() {
return Book_no;
}
};
//function to return Book_name
char* Rbook_name() {
return Book_name;
}Main.cpp
//==============================================================
// Name : Question47279.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//==============================================================
#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <string>
#include <fstream>
#include <vector>
#include "Book.h"
using namespace std;
const int DELETED = -1;
vector<Book> books;
void read() {
ifstream in("test.dat");
if (!in.good()) {
return;
}
while (!in.eof())
{
Book curBook = Book();
in >> curBook.Book_no;
in >> curBook.Book_name;
books.push_back(curBook);
}
in.close();
size_t booksAmount = books.size();
for (size_t i = 0; i < booksAmount; ++i) {
books[i].showdetails();
}
}
void rewriteFile() {
ofstream outfile;
outfile.open("test.dat");
size_t nBooks = books.size();
for (size_t i = 0; i < nBooks; ++i) {
if (books[i].Book_no != DELETED) {
outfile << books[i].Book_no << books[i].Book_name;
}
}
}
void appendBook() {
Book newBook = Book();
newBook.enterdetails();
books.push_back(newBook);
rewriteFile();
}
void modifyBook() {
cout << "Enter book No ";
int n;
cin >> n;
if (n > 0) {
int found = DELETED;
size_t nBooks = books.size();
for (size_t i = 0; i < nBooks; ++i) {
if (books[i].Book_no == n) {
found = i;
}
}
if (found != DELETED) {
cout << "Enter new name ";
cin >> books[found].Book_name;
}
}
rewriteFile();
}
void searchBook() {
cout << "Enter book name ";
char val[20];
cin >> val;
bool found = false;
size_t nBooks = books.size();
for (size_t i = 0; i < nBooks; ++i) {
if (strcmp(books[i].Book_name, val) == 0) {
books[i].showdetails();
found = true;
}
}
if (!found) {
cout<<"No results found"<<endl;
}
rewriteFile();
}
void deleteBook() {
cout<<"Enter book No ";
int n;
cin>>n;
if (n > 0) {
size_t nBooks = books.size();
for (size_t i = 0; i < nBooks; ++i) {
if (books[i].Book_no == n) {
books[i].Book_no = DELETED;
}
}
}
rewriteFile();
}
int main() {
char res = ' ';
bool quit = false;
while (!quit) {
cout<<"---Content of dat file---"<<endl<<endl;
read();
cout<<endl<<"---"<<endl;
cout<<"What do you want to do?"<<endl;
cout<<"1 - Add new book"<<endl;
cout<<"2 - Modify book"<<endl;
cout<<"3 - Delete book"<<endl;
cout<<"4 - Search book"<<endl;
cout<<"q - Quit"<<endl;
cin>>res;
switch (res) {
case '1':
appendBook();
break;
case '2':
modifyBook();
break;
case '3':
deleteBook();
break;
case '4':
searchBook();
break;
case 'q':
quit = true;
break;
}
}
return 0;
}
Comments