← العودة إلى الدورة: Modern C++ from scratch

Final project: console inventory system

الفيديو قريبًا

You have reached the end of the course, and it is time to join everything you learned in a complete, organized project: an inventory system for a shop that works in the console. The program manages products with name, price and quantity; it lets you add, sell, remove and list; it computes the total value of the stock; and it warns about products with low stock. You will use classes and encapsulation, STL containers, exceptions, algorithms, several files and CMake. First read the whole statement, try to solve each part yourself and use the reference code only to compare.

Requirements

  • Structure: include/product.h, include/store.h, src/store.cpp, src/main.cpp and a CMakeLists.txt in C++17 with warnings enabled.
  • Product is a struct with name, price (double) and quantity (int).
  • Store keeps the products in a std::map sorted by name and hides that detail (private member).
  • Store offers add, remove, find, sell, size, totalValue, list and lowStock.
  • add validates the data (non-negative price and quantity) and, if the product already exists, adds the quantity.
  • remove and sell throw std::out_of_range if the product does not exist; invalid data throws std::invalid_argument.
  • main reads commands from the console in a loop: add, sell, remove, list, low, total, quit; errors are caught and shown without closing the program.
  • No new or delete, no leaks, no using namespace std in headers.

Reference code: headers

cpp
// ---- include/product.h ----
#pragma once

#include <string>

struct Product {
    std::string name;
    double price{0.0};
    int quantity{0};
};
cpp
// ---- include/store.h ----
#pragma once

#include <cstddef>
#include <map>
#include <string>
#include <vector>

#include "product.h"

class Store {
public:
    void add(const Product& product);                   // adds or merges quantity
    void remove(const std::string& name);               // throws std::out_of_range
    const Product* find(const std::string& name) const; // nullptr if missing
    bool sell(const std::string& name, int amount);     // false if not enough stock
    std::size_t size() const;
    double totalValue() const;
    std::vector<Product> list() const;                  // sorted by name
    std::vector<Product> lowStock(int limit) const;     // quantity <= limit

private:
    std::map<std::string, Product> products_;
};

Reference code: implementation

cpp
// ---- src/store.cpp ----
#include "store.h"

#include <numeric>
#include <stdexcept>

void Store::add(const Product& product) {
    if (product.name.empty() || product.price < 0 || product.quantity < 0) {
        throw std::invalid_argument{"invalid product data"};
    }
    auto [it, inserted] = products_.try_emplace(product.name, product);
    if (!inserted) {
        it->second.quantity += product.quantity;
        it->second.price = product.price;   // the latest price wins
    }
}

void Store::remove(const std::string& name) {
    if (products_.erase(name) == 0) {
        throw std::out_of_range{"unknown product: " + name};
    }
}

const Product* Store::find(const std::string& name) const {
    auto it = products_.find(name);
    return it == products_.end() ? nullptr : &it->second;
}

bool Store::sell(const std::string& name, int amount) {
    if (amount <= 0) {
        throw std::invalid_argument{"amount must be positive"};
    }
    auto it = products_.find(name);
    if (it == products_.end()) {
        throw std::out_of_range{"unknown product: " + name};
    }
    if (it->second.quantity < amount) {
        return false;
    }
    it->second.quantity -= amount;
    return true;
}

std::size_t Store::size() const { return products_.size(); }

double Store::totalValue() const {
    return std::accumulate(products_.begin(), products_.end(), 0.0,
                           [](double acc, const auto& entry) {
                               return acc + entry.second.price * entry.second.quantity;
                           });
}

std::vector<Product> Store::list() const {
    std::vector<Product> result;
    result.reserve(products_.size());
    for (const auto& [name, product] : products_) {
        result.push_back(product);
    }
    return result;
}

std::vector<Product> Store::lowStock(int limit) const {
    std::vector<Product> result;
    for (const auto& [name, product] : products_) {
        if (product.quantity <= limit) {
            result.push_back(product);
        }
    }
    return result;
}
cpp
// ---- src/main.cpp ----
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>

#include "store.h"

namespace {

void printProducts(const std::vector<Product>& products) {
    if (products.empty()) {
        std::cout << "(nothing to show)\n";
        return;
    }
    for (const Product& p : products) {
        std::cout << std::left << std::setw(14) << p.name << std::right
                  << std::setw(9) << std::fixed << std::setprecision(2) << p.price
                  << std::setw(6) << p.quantity << '\n';
    }
}

// returns false when the user wants to leave
bool handleCommand(Store& store, const std::string& line) {
    std::istringstream in{line};
    std::string command;
    in >> command;

    if (command.empty()) {
        return true;
    }
    if (command == "quit") {
        return false;
    }
    if (command == "add") {
        Product p;
        if (!(in >> p.name >> p.price >> p.quantity)) {
            std::cout << "usage: add <name> <price> <quantity>\n";
            return true;
        }
        store.add(p);
        std::cout << "ok\n";
    } else if (command == "sell") {
        std::string name;
        int amount{0};
        if (!(in >> name >> amount)) {
            std::cout << "usage: sell <name> <amount>\n";
            return true;
        }
        std::cout << (store.sell(name, amount) ? "sold" : "not enough stock") << '\n';
    } else if (command == "remove") {
        std::string name;
        if (!(in >> name)) {
            std::cout << "usage: remove <name>\n";
            return true;
        }
        store.remove(name);
        std::cout << "removed\n";
    } else if (command == "list") {
        printProducts(store.list());
    } else if (command == "low") {
        int limit{0};
        if (!(in >> limit)) {
            std::cout << "usage: low <limit>\n";
            return true;
        }
        printProducts(store.lowStock(limit));
    } else if (command == "total") {
        std::cout << "total value: " << std::fixed << std::setprecision(2)
                  << store.totalValue() << '\n';
    } else {
        std::cout << "unknown command: " << command << '\n';
    }
    return true;
}

}  // namespace

int main() {
    Store store;
    std::cout << "inventory ready (add, sell, remove, list, low, total, quit)\n";

    std::string line;
    while (std::cout << "> " && std::getline(std::cin, line)) {
        try {
            if (!handleCommand(store, line)) {
                break;
            }
        } catch (const std::exception& e) {
            std::cout << "error: " << e.what() << '\n';   // the program keeps running
        }
    }
    std::cout << "bye\n";
    return 0;
}
cmake
cmake_minimum_required(VERSION 3.16)
project(InventoryProject LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

add_executable(inventory src/main.cpp src/store.cpp)
target_include_directories(inventory PRIVATE include)

if(MSVC)
    target_compile_options(inventory PRIVATE /W4)
else()
    target_compile_options(inventory PRIVATE -Wall -Wextra -Wpedantic)
endif()

Suggested steps and completion criteria

  • Step 1: create the folders and empty files, write the CMakeLists.txt and check that a main that only prints a message compiles.
  • Step 2: write Product and the Store declaration; implement add, size and find, and test them from main before continuing.
  • Step 3: add sell, remove and the exceptions; test the error cases on purpose.
  • Step 4: implement totalValue, list and lowStock with the STL.
  • Step 5: write the command loop with istringstream and catch the exceptions.
  • Step 6: compile with warnings and, if you can, with -fsanitize=address,undefined; fix everything that shows up.
  • Done when: it compiles with no warnings; all commands work; errors do not close the program; you use no new or delete; and each class protects its data.

An example session: add pen 1.5 10, add notebook 3.2 5, sell pen 4, list (shows notebook and pen sorted), total (shows 25.00, because 6 pens at 1.50 plus 5 notebooks at 3.20 add up to 25), sell ghost 1 (shows "error: unknown product: ghost" and the program keeps going) and quit. Notice that the map stores the products sorted by name, so list does not need to sort anything. When everything works, improve the project at your own pace: save and load the inventory in a text file with std::fstream, add a command to search by prefix, allow spaces in names or write tests with assert for each rule of Store.

اختبر ما تعلمته

السؤال 1 من 8

Why does Store keep the products in a private member?

✎ ملاحظاتي

محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف

← السابق