1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
#include <iostream> #include <vector> #include <string> using namespace std; class Book { public: string title; string author; bool isAvailable; Book(const string& t, const string& a) : title(t), author(a), isAvailable(true) {} }; class Library { private: vector<Book> books; public: void addBook(const string& title, const string& author) { books.emplace_back(title, author); cout << "Book added: " << title << " by " << author << endl; } void borrowBook(const string& title) { for (auto& book : books) { if (book.title == title) { if (book.isAvailable) { book.isAvailable = false; cout << "You have borrowed: " << title << endl; return; } else { cout << "Sorry, the book is not available right now." << endl; return; } } } cout << "Book not found." << endl; } void returnBook(const string& title) { for (auto& book : books) { if (book.title == title) { if (!book.isAvailable) { book.isAvailable = true; cout << "You have returned: " << title << endl; return; } else { cout << "This book was not borrowed." << endl; return; } } } cout << "Book not found." << endl; } void listBooks() const { cout << "Library Books:" << endl; for (const auto& book : books) { cout << "Title: " << book.title << ", Author: " << book.author << ", " << (book.isAvailable ? "Available" : "Not Available") << endl; } } }; int main() { Library library; library.addBook("1984", "George Orwell"); library.addBook("To Kill a Mockingbird", "Harper Lee"); library.listBooks(); library.borrowBook("1984"); library.listBooks(); library.returnBook("1984"); library.listBooks(); return 0; } |
Explanation
- Book Class: Represents a book with attributes for the title, author, and availability status.
title
Advertisementauthor
: The author of the book.isAvailable
: A boolean indicating if the book is available for borrowing.
- Library Class: Manages a collection of books and provides functionality for adding, borrowing, returning, and listing books.
addBook
: Adds a new book to the library with the given title and author.borrowBook
: Changes the status of a book to borrowed if it’s available. Displays a message if the book is not available or not found.returnBook
: Changes the status of a book to available if it was borrowed. Displays a message if the book was not borrowed or not found.listBooks
: Lists all books in the library with their availability status.
Advertisement - Main Function:
- Creates an instance of the
Library
class. - Adds a couple of books to the library.
- Lists the books in the library.
- Borrows a book and shows updated status.
- Returns the book and shows updated status again.
- Creates an instance of the