I'm having an assignment where I have to make a book library in C++ using several classes through an inheritance heirarchy as well as composition. I'm stuck at one place where it asks that each book should have a unique ISBN and that if I enter an ISBN that already exists, it should produce an error. Can someone tell me how to put that check in a class that it doesn't allow a data member to have the same value.
ok. so you have a book class which will have a name and a ISBN number.
Now you will be having a library which will have a list of books. So something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class book
{
name;
isbn ;
};
class library
{
private:
book m_list_of_books;
public:
bool AddBook(name, isbn);
};
Now the question is, how will you keep the list of books inside the library?
if you can answer this question, then you have to search that list for the isbn number. If you find that number your AddBook() function will return false and will not add thebook else the book will be added to the m_list_of_books.
So you will do:
1 2 3 4
if(!library::AddBook(isbn))
print "Error: already added";
else
print "Success: book added to library";
writetonsharma didn't give you a solution but rather explained how you should put the solution in your code.
It is a good idea to have AddBook return a boolean to let user know whether the book was added or not.
You need a function
1 2 3 4
bool Book::find( constchar* name ) {
for( int i = 0; i < 20; i++ ) if( strcmp( title[i], name ) != 0 ) returntrue;
returntrue;
}
and then in your AddBook write first line if( find(a) ) returnfalse; (or just return if you choose AddBook not to return anything, of course).
Now when you try to push in the list, you have to use algorithm:
1 2 3 4 5 6
Book b("title");
if(std::find(BookList.begin(), BookList.end(), b) == BookList.end())
//book not found,
m_BookList.push_back(b);
else
//book found, dont add it.