Darekdari / C++ Projects

C++ Project for Beginners: Library Management System

Create a system that lets library users manage books. Users can add books, search by title, author or ISBN, borrow and return books with a library card number, and view the available and borrowed books. It is a classic C++ project for beginners that practices classes, vectors and input validation. Read the code, try the live demo, then add the optional enhancements.

Classes & vectorsLive demoPortfolio readyBeginner friendly
01 / Overview

How the C++ Library Management System Works

The project has two classes. Book stores the title, author, ISBN, publication year, availability and the card number of the borrower. Library keeps a std::vector<Book> and provides the operations. A text menu in main() is the user interface.

Requirements covered

  • Add books with title, author, ISBN and year (duplicate ISBNs are rejected).
  • Search by title, author or ISBN.
  • Track availability of every book: available or borrowed.
  • Borrow with a library card number and an ISBN.
  • Return with an ISBN.
  • Display all books, the available books, the borrowed books and the details of one book.
What changed from the original: the original code could only list the books and borrow one book once, then the program ended. It had no menu, no library card number, no return, no search, no list of borrowed books and no book details. This version adds all of them, tracks who borrowed each book, rejects duplicate ISBNs and validates input.
02 / The Book class

Step 1: Helpers and the Book Class

Start with the includes, three input helpers and the Book class. readInt() keeps asking until the number is in range and readLine() refuses empty text. borrow() and giveBack() change the availability and remember the borrower, so the class protects its own data.

main.cpp
#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <string>
#include <vector>

// Read a non-empty line of text
std::string readLine(const std::string& prompt) {
    std::string line;
    do {
        std::cout << prompt;
        if (!std::getline(std::cin, line)) std::exit(0); // input closed
    } while (line.empty());
    return line;
}

// Read an integer between min and max
int readInt(const std::string& prompt, int min, int max) {
    int value;
    while (true) {
        std::cout << prompt;
        if (std::cin >> value && value >= min && value <= max) {
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            return value;
        }
        if (std::cin.eof()) std::exit(0);
        std::cout << "Please enter a number between " << min << " and " << max << ".\n";
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
}

std::string toLower(std::string text) {
    std::transform(text.begin(), text.end(), text.begin(),
                   [](unsigned char c) { return std::tolower(c); });
    return text;
}

class Book {
private:
    std::string title;
    std::string author;
    std::string isbn;
    int publicationYear;
    bool isAvailable;
    std::string borrowedBy; // library card number, empty when available
    int borrowCount;

public:
    Book(const std::string& title, const std::string& author, const std::string& isbn,
         int publicationYear)
        : title(title), author(author), isbn(isbn), publicationYear(publicationYear),
          isAvailable(true), borrowedBy(""), borrowCount(0) {}

    std::string getTitle() const { return title; }
    std::string getAuthor() const { return author; }
    std::string getISBN() const { return isbn; }
    int getPublicationYear() const { return publicationYear; }
    bool getAvailability() const { return isAvailable; }
    std::string getBorrowedBy() const { return borrowedBy; }
    int getBorrowCount() const { return borrowCount; }

    void borrow(const std::string& cardNumber) {
        isAvailable = false;
        borrowedBy = cardNumber;
        borrowCount++;
    }

    void giveBack() {
        isAvailable = true;
        borrowedBy = "";
    }

    void displayDetails() const {
        std::cout << "Title: " << title << std::endl;
        std::cout << "Author: " << author << std::endl;
        std::cout << "ISBN: " << isbn << std::endl;
        std::cout << "Publication Year: " << publicationYear << std::endl;
        std::cout << "Availability: " << (isAvailable ? "Available" : "Borrowed") << std::endl;
        if (!isAvailable) {
            std::cout << "Borrowed by card: " << borrowedBy << std::endl;
        }
    }
};
03 / The Library class

Step 2: The Library Class

This class owns the vector. findBookByISBN() returns a pointer, or nullptr when nothing matches, so borrowing and returning change the real book and not a copy. Borrow and return give back a Result, which lets main() print the right message without the class doing any printing. Search ignores case and matches part of the text.

main.cpp (continued)
enum class Result { Ok, NotFound, Unavailable, NotBorrowed };
enum class SearchBy { Title, Author };

class Library {
private:
    std::vector<Book> books;

public:
    bool addBook(const Book& book) {
        if (findBookByISBN(book.getISBN()) != nullptr) {
            return false; // ISBN already exists
        }
        books.push_back(book);
        return true;
    }

    Book* findBookByISBN(const std::string& isbn) {
        for (auto& book : books) {
            if (book.getISBN() == isbn) {
                return &book;
            }
        }
        return nullptr;
    }

    std::vector<Book> allBooks() const { return books; }

    std::vector<Book> booksByAvailability(bool available) const {
        std::vector<Book> found;
        for (const auto& book : books) {
            if (book.getAvailability() == available) {
                found.push_back(book);
            }
        }
        return found;
    }

    std::vector<Book> search(SearchBy by, const std::string& text) const {
        std::vector<Book> found;
        const std::string needle = toLower(text);
        for (const auto& book : books) {
            const std::string field = (by == SearchBy::Title) ? book.getTitle() : book.getAuthor();
            if (toLower(field).find(needle) != std::string::npos) {
                found.push_back(book);
            }
        }
        return found;
    }

    Result borrowBook(const std::string& isbn, const std::string& cardNumber) {
        Book* book = findBookByISBN(isbn);
        if (book == nullptr) return Result::NotFound;
        if (!book->getAvailability()) return Result::Unavailable;
        book->borrow(cardNumber);
        return Result::Ok;
    }

    Result returnBook(const std::string& isbn) {
        Book* book = findBookByISBN(isbn);
        if (book == nullptr) return Result::NotFound;
        if (book->getAvailability()) return Result::NotBorrowed;
        book->giveBack();
        return Result::Ok;
    }
};
04 / The menu

Step 3: The Menu and main()

The user interface is a loop that shows a menu and runs the chosen action until the user picks 0. Every action reads input with the helpers from Step 1. Compile with g++ -std=c++11 main.cpp -o library and run ./library.

main.cpp (continued)
void printBooks(const std::vector<Book>& list, const std::string& emptyMessage) {
    if (list.empty()) {
        std::cout << emptyMessage << std::endl;
        return;
    }
    for (const auto& book : list) {
        std::cout << "---------------------" << std::endl;
        book.displayDetails();
    }
    std::cout << "---------------------" << std::endl;
}

int main() {
    Library library;

    // Sample data
    library.addBook(Book("The Great Gatsby", "F. Scott Fitzgerald", "9780743273565", 1925));
    library.addBook(Book("To Kill a Mockingbird", "Harper Lee", "9780061120084", 1960));
    library.addBook(Book("1984", "George Orwell", "9780451524935", 1949));

    int choice;
    do {
        std::cout << "\n=== Library Management System ===\n"
                  << "1. Add book\n2. Show all books\n3. Show available books\n"
                  << "4. Show borrowed books\n5. Search books\n6. View book details\n"
                  << "7. Borrow book\n8. Return book\n0. Exit\n";
        choice = readInt("Choose an option: ", 0, 8);

        switch (choice) {
        case 1: {
            std::string title = readLine("Title: ");
            std::string author = readLine("Author: ");
            std::string isbn = readLine("ISBN: ");
            int year = readInt("Publication year (1000-2100): ", 1000, 2100);
            if (library.addBook(Book(title, author, isbn, year))) {
                std::cout << "Book added successfully!\n";
            } else {
                std::cout << "A book with that ISBN already exists.\n";
            }
            break;
        }
        case 2:
            printBooks(library.allBooks(), "The library has no books.");
            break;
        case 3:
            printBooks(library.booksByAvailability(true), "No books are available.");
            break;
        case 4:
            printBooks(library.booksByAvailability(false), "No books are currently borrowed.");
            break;
        case 5: {
            std::cout << "Search by: 1) Title  2) Author  3) ISBN\n";
            int by = readInt("Choose: ", 1, 3);
            if (by == 1) {
                printBooks(library.search(SearchBy::Title, readLine("Title contains: ")),
                           "No books found.");
            } else if (by == 2) {
                printBooks(library.search(SearchBy::Author, readLine("Author contains: ")),
                           "No books found.");
            } else {
                const Book* book = library.findBookByISBN(readLine("ISBN: "));
                if (book != nullptr) book->displayDetails();
                else std::cout << "Book not found in the library.\n";
            }
            break;
        }
        case 6: {
            const Book* book = library.findBookByISBN(readLine("ISBN: "));
            if (book != nullptr) book->displayDetails();
            else std::cout << "Book not found in the library.\n";
            break;
        }
        case 7: {
            std::string card = readLine("Library card number: ");
            Result result = library.borrowBook(readLine("ISBN of the book to borrow: "), card);
            if (result == Result::Ok) std::cout << "Book borrowed successfully!\n";
            else if (result == Result::Unavailable) std::cout << "Book is not available for borrowing.\n";
            else std::cout << "Book not found in the library.\n";
            break;
        }
        case 8: {
            Result result = library.returnBook(readLine("ISBN of the book to return: "));
            if (result == Result::Ok) std::cout << "Book returned successfully!\n";
            else if (result == Result::NotBorrowed) std::cout << "That book was not borrowed.\n";
            else std::cout << "Book not found in the library.\n";
            break;
        }
        }
    } while (choice != 0);

    std::cout << "Goodbye!\n";
    return 0;
}
05 / Try it

Live Demo: Run the Library in Your Browser

This demo follows the same rules as the C++ code: unique ISBNs, a library card number to borrow, return by ISBN, and search by title, author or ISBN. Data lives in memory, so a refresh resets it.

TitleAuthorISBNYearStatusActions
Press Details on a book to see everything about it.
0Books
0Available
0Borrowed
06 / Enhancements

Optional Enhancements with Solutions

Here is how to add each optional feature to the C++ version. Try each one yourself first.

1. Reserve a book that is borrowed

Give each Book a queue of card numbers. When the book is returned, it goes straight to the first person in the queue.

solution.cpp
// In class Book (private member and public methods)
std::vector<std::string> reservations;

void reserve(const std::string& cardNumber) { reservations.push_back(cardNumber); }
bool hasReservations() const { return !reservations.empty(); }
std::string popReservation() {
    std::string first = reservations.front();
    reservations.erase(reservations.begin());
    return first;
}

// In Library::returnBook, after book->giveBack():
if (book->hasReservations()) {
    std::string next = book->popReservation();
    book->borrow(next);
    std::cout << "The book was passed to card " << next << ".\n";
}
2. Report: the most borrowed books

The borrowCount field is already in Book. Sort a copy of the vector by it and keep the top results. For a ratings report, add a rating field the same way.

solution.cpp
std::vector<Book> mostBorrowed(size_t top) const {
    std::vector<Book> sorted = books;
    std::sort(sorted.begin(), sorted.end(),
        [](const Book& a, const Book& b) { return a.getBorrowCount() > b.getBorrowCount(); });
    if (sorted.size() > top) {
        sorted.erase(sorted.begin() + top, sorted.end());
    }
    return sorted;
}
3. Show the books borrowed by one card

Filter the borrowed books by the card number, so a reader can see what they still have.

solution.cpp
std::vector<Book> booksBorrowedBy(const std::string& cardNumber) const {
    std::vector<Book> found;
    for (const auto& book : books) {
        if (!book.getAvailability() && book.getBorrowedBy() == cardNumber) {
            found.push_back(book);
        }
    }
    return found;
}
4. Librarian login

Ask for a password before adding books. This is a learning example only: real systems never store a plain-text password in the source code.

solution.cpp
bool loginAsLibrarian() {
    std::string password = readLine("Librarian password: ");
    return password == "library123"; // demo only
}

// in main(), at the start of case 1:
// if (!loginAsLibrarian()) { std::cout << "Access denied.\n"; break; }

Looking for more C++ projects? Browse our C++ projects and the free practice sets.

07 / FAQ

Frequently Asked Questions About the C++ Library Management System

How does a library management system track borrowed books?

Each Book object stores an availability flag and the library card number of the borrower. Borrowing sets the flag to false and saves the card number, and returning clears both. The list of borrowed books is every book whose flag is false.

Why does findBookByISBN return a pointer?

A pointer lets the caller change the real book stored in the vector instead of a copy, and nullptr clearly means that no book was found.

How do you search case-insensitively in C++?

Convert both the stored text and the search text to lower case with std::transform and std::tolower, then use std::string::find. Step 1 has a toLower() helper.

How long does it take to learn C++?

Most beginners learn the basics (variables, functions, loops, classes) in a few months of regular practice. Small projects like this one speed it up.

Conclusion

Keep Building with C++

You built a library management system with classes, a vector, input validation and a text menu. Next, save the books to a file so they survive after the program closes, or add due dates and fines. Small projects like this are the fastest way to learn C++.

Learn more

More info about us

Scroll to Top