Untitled
unknown
plain_text
2 years ago
2.1 kB
36
Indexable
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Book {
string title;
string author;
int year;
};
class Library {
private:
vector<Book> books;
public:
void addBook(const Book& book) {
books.push_back(book);
}
void removeBook(const string& title) {
for (auto it = books.begin(); it != books.end(); ++it) {
if (it->title == title) {
books.erase(it);
cout << "Book removed successfully." << endl;
return;
}
}
cout << "Book not found." << endl;
}
void searchBook(const string& title) {
for (const auto& book : books) {
if (book.title == title) {
cout << "Book found: " << endl;
cout << "Title: " << book.title << endl;
cout << "Author: " << book.author << endl;
cout << "Year: " << book.year << endl;
return;
}
}
cout << "Book not found." << endl;
}
void displayBooks() {
if (books.empty()) {
cout << "No books in the library." << endl;
return;
}
cout << "Books in the library: " << endl;
for (const auto& book : books) {
cout << "Title: " << book.title << endl;
cout << "Author: " << book.author << endl;
cout << "Year: " << book.year << endl;
cout << "-----------------------" << endl;
}
}
};
int main() {
Library library;
// Adding books
Book book1 = { "The Catcher in the Rye", "J.D. Salinger", 1951 };
library.addBook(book1);
Book book2 = { "To Kill a Mockingbird", "Harper Lee", 1960 };
library.addBook(book2);
Book book3 = { "1984", "George Orwell", 1949 };
library.addBook(book3);
// Displaying books
library.displayBooks();
// Searching for a book
library.searchBook("To Kill a Mockingbird");
// Removing a book
library.removeBook("1984");
// Displaying books after removal
library.displayBooks();
return 0;
}
Editor is loading...