Skip to main content

Lesson 4 of 7

main.cpp - CLI Loop & Complete Integration

The `main.cpp` wires together all subsystems into a CLI loop. It demonstrates: command parsing with `switch` and `string_view`, exception handling at the application boundary, formatted table output with `<iomanip>`, the complete product creation factory, and how all 11 modules come together in a working application.

15 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Complete main.cpp - CLI Inventory Management System

Complete main.cpp - CLI Inventory Management System
// โ”€โ”€ src/main.cpp - Complete CLI IMS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
#include <iostream>
#include <string>
#include <string_view>
#include <memory>
#include <vector>
#include <iomanip>
#include <sstream>
#include <algorithm>
#include <numeric>

// Project headers (simplified inline for learning demo)
// In a real project: #include "inventory.h", "filestore.h", etc.

// โ”€โ”€โ”€ Simplified Complete Demo (all in one file for clarity) โ”€โ”€โ”€

// Product base (simplified from Module 4)
class Product {
    static int next_id_;
    int         id_;
    std::string name_;
    std::string category_;
    double      price_;
    int         quantity_;

public:
    Product(std::string name, std::string cat, double price, int qty)
        : id_(++next_id_)
        , name_(std::move(name))
        , category_(std::move(cat))
        , price_(price)
        , quantity_(qty)
    {
        if (price_ < 0) throw std::invalid_argument("Negative price");
        if (quantity_ < 0) throw std::invalid_argument("Negative qty");
    }
    virtual ~Product() = default;

    int                  id()       const noexcept { return id_; }
    const std::string&   name()     const noexcept { return name_; }
    const std::string&   category() const noexcept { return category_; }
    double               price()    const noexcept { return price_; }
    int                  quantity() const noexcept { return quantity_; }
    double               value()    const noexcept { return price_ * quantity_; }

    void set_price(double p)    { if (p<0) throw std::invalid_argument("neg price"); price_ = p; }
    void adjust_qty(int delta)  {
        if (quantity_ + delta < 0) throw std::invalid_argument("qty below zero");
        quantity_ += delta;
    }

    bool operator<(const Product& o) const noexcept { return name_ < o.name_; }
};
int Product::next_id_ = 0;

// Formatted table output
static void print_row(const Product& p) {
    std::cout << std::left
              << std::setw(4)  << p.id()
              << std::setw(22) << p.name()
              << std::setw(12) << p.category()
              << std::right
              << std::setw(9)  << std::fixed << std::setprecision(2) << p.price()
              << std::setw(8)  << p.quantity()
              << std::setw(12) << p.value()
              << "
";
}

static void print_header() {
    std::cout << std::left
              << std::setw(4)  << "ID"
              << std::setw(22) << "Name"
              << std::setw(12) << "Category"
              << std::right
              << std::setw(9)  << "Price"
              << std::setw(8)  << "Qty"
              << std::setw(12) << "Value"
              << "
"
              << std::string(67, '-') << "
";
}

static void show_help() {
    std::cout << "
Commands:
"
              << "  list                    - list all products
"
              << "  add <name> <cat> <p> <q>- add product
"
              << "  find <id>               - find by id
"
              << "  remove <id>             - remove by id
"
              << "  buy <id> <qty>          - decrease quantity (sale)
"
              << "  restock <id> <qty>      - increase quantity
"
              << "  filter <cat>            - filter by category
"
              << "  sort <name|price|value> - sort products
"
              << "  stats                   - inventory statistics
"
              << "  help                    - show this help
"
              << "  quit                    - exit

";
}

int main() {
    std::vector<std::unique_ptr<Product>> inventory;
    std::unordered_map<int, Product*>    id_idx;

    auto add_product = [&](std::unique_ptr<Product> p) {
        id_idx[p->id()] = p.get();
        inventory.push_back(std::move(p));
    };

    // Seed with sample data
    add_product(std::make_unique<Product>("C++ Primer",      "Books",       49.99,  25));
    add_product(std::make_unique<Product>("Mechanical Keyboard","Electronics",129.99, 10));
    add_product(std::make_unique<Product>("USB-C Cable",     "Electronics", 14.99, 100));
    add_product(std::make_unique<Product>("Standing Desk",   "Furniture",  399.00,   5));
    add_product(std::make_unique<Product>("Notebook",        "Stationery",   4.99,  50));

    std::cout << "โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
"
              << "โ•‘         C++ Inventory Management System v1.0         โ•‘
"
              << "โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
";
    show_help();

    std::string line;
    while (true) {
        std::cout << "ims> ";
        if (!std::getline(std::cin, line)) break;

        std::istringstream iss(line);
        std::string cmd;
        iss >> cmd;

        try {
            if (cmd == "quit" || cmd == "exit") break;

            else if (cmd == "help") show_help();

            else if (cmd == "list") {
                if (inventory.empty()) { std::cout << "(empty)
"; continue; }
                print_header();
                // Sort by name (using lambda + sort on raw pointers)
                std::vector<Product*> sorted;
                std::transform(inventory.begin(), inventory.end(),
                               std::back_inserter(sorted),
                               [](const auto& p){ return p.get(); });
                std::sort(sorted.begin(), sorted.end(),
                          [](const Product* a, const Product* b){ return *a < *b; });
                for (const auto* p : sorted) print_row(*p);
                std::cout << std::string(67, '-') << "
"
                          << "Total products: " << inventory.size() << "
";

            } else if (cmd == "add") {
                std::string name, cat;
                double price; int qty;
                if (!(iss >> name >> cat >> price >> qty)) {
                    std::cerr << "Usage: add <name> <cat> <price> <qty>
";
                    continue;
                }
                add_product(std::make_unique<Product>(name, cat, price, qty));
                std::cout << "Added product #" << inventory.back()->id() << "
";

            } else if (cmd == "find") {
                int id; iss >> id;
                auto it = id_idx.find(id);
                if (it == id_idx.end()) {
                    std::cerr << "Product #" << id << " not found
"; continue;
                }
                print_header(); print_row(*it->second);

            } else if (cmd == "remove") {
                int id; iss >> id;
                auto it = id_idx.find(id);
                if (it == id_idx.end()) { std::cerr << "Not found
"; continue; }
                id_idx.erase(it);
                inventory.erase(std::remove_if(inventory.begin(), inventory.end(),
                    [id](const auto& p){ return p->id() == id; }),
                    inventory.end());
                std::cout << "Removed #" << id << "
";

            } else if (cmd == "buy" || cmd == "restock") {
                int id, qty; iss >> id >> qty;
                auto it = id_idx.find(id);
                if (it == id_idx.end()) { std::cerr << "Not found
"; continue; }
                it->second->adjust_qty(cmd == "buy" ? -qty : qty);
                std::cout << "Updated. New qty: " << it->second->quantity() << "
";

            } else if (cmd == "filter") {
                std::string cat; iss >> cat;
                std::vector<Product*> results;
                std::copy_if(inventory.begin(), inventory.end(),
                             std::back_inserter(results),
                             [&cat](const auto& p){ return p->category() == cat; });
                if (results.empty()) { std::cout << "No products in category: " << cat << "
"; continue; }
                print_header();
                for (const auto* p : results) print_row(*p); // pointing to unique_ptr
                // Fix: filter raw pointers
                results.clear();
                for (const auto& up : inventory) {
                    if (up->category() == cat) results.push_back(up.get());
                }
                for (const auto* p : results) print_row(*p);

            } else if (cmd == "sort") {
                std::string key; iss >> key;
                std::vector<Product*> sorted;
                for (const auto& p : inventory) sorted.push_back(p.get());
                if (key == "name") {
                    std::sort(sorted.begin(), sorted.end(),
                              [](const Product* a, const Product* b){ return *a < *b; });
                } else if (key == "price") {
                    std::sort(sorted.begin(), sorted.end(),
                              [](const Product* a, const Product* b){ return a->price() < b->price(); });
                } else if (key == "value") {
                    std::sort(sorted.begin(), sorted.end(),
                              [](const Product* a, const Product* b){ return a->value() > b->value(); });
                }
                print_header();
                for (const auto* p : sorted) print_row(*p);

            } else if (cmd == "stats") {
                double total_val = std::accumulate(inventory.begin(), inventory.end(), 0.0,
                    [](double acc, const auto& p){ return acc + p->value(); });
                int total_qty = std::accumulate(inventory.begin(), inventory.end(), 0,
                    [](int acc, const auto& p){ return acc + p->quantity(); });
                auto [mn, mx] = std::minmax_element(inventory.begin(), inventory.end(),
                    [](const auto& a, const auto& b){ return a->price() < b->price(); });
                std::cout << std::fixed << std::setprecision(2);
                std::cout << "Products:    " << inventory.size() << "
";
                std::cout << "Total qty:   " << total_qty << "
";
                std::cout << "Total value: $" << total_val << "
";
                if (!inventory.empty()) {
                    std::cout << "Cheapest:    " << (*mn)->name() << " $" << (*mn)->price() << "
";
                    std::cout << "Priciest:    " << (*mx)->name() << " $" << (*mx)->price() << "
";
                }

            } else if (!cmd.empty()) {
                std::cerr << "Unknown command: " << cmd << " (type 'help')
";
            }

        } catch (const std::exception& e) {
            std::cerr << "Error: " << e.what() << "
";
        }
    }

    std::cout << "Goodbye!
";
    return 0;
}

Common Mistakes

  • **Mixing ownership in the filter operation** - the filter lambda should work on the `unique_ptr` items and return raw observer pointers. `std::copy_if` with `back_inserter` on a `vector<Product*>`: the lambda takes `const unique_ptr<Product>&` and returns the Boolean condition, while the target vector holds `Product*` (raw observer). The example above double-prints - in production, do the filter once cleanly.
  • **Not resetting `next_id_` for tests** - the static `next_id_` persists between test cases. For testable code, provide a `static void reset()` method or use a non-static counter passed via factory. Static state makes unit testing difficult.
  • **Error handling at the wrong level** - catching `std::exception` in the CLI loop is correct: let lower-level functions throw and catch at the user-interaction boundary. Don't catch inside every function - only at boundaries where you can meaningfully handle or report the error.

Tip

Tip

Practice maincpp CLI Loop Complete Integration in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagramโ€ฆ

Top-Level try/catch Boundary, Input State Machine, and Command Pattern Execution

Practice Task

Note

Practice Task - (1) Write a working example of maincpp CLI Loop Complete Integration from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with maincpp CLI Loop Complete Integration is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.

Key Takeaways

  • *Mixing ownership in the filter operation** - the filter lambda should work on the `unique_ptr` items and return raw observer pointers. `std::copy_if` with `back_inserter` on a `vector<Product*>`: the lambda takes `const unique_ptr<Product>&` and returns the Boolean condition, while the target vector holds `Product*` (raw observer). The example above double-prints - in production, do the filter once cleanly.
  • *Not resetting `next_id_` for tests** - the static `next_id_` persists between test cases. For testable code, provide a `static void reset()` method or use a non-static counter passed via factory. Static state makes unit testing difficult.
  • *Error handling at the wrong level** - catching `std::exception` in the CLI loop is correct: let lower-level functions throw and catch at the user-interaction boundary. Don't catch inside every function - only at boundaries where you can meaningfully handle or report the error.

Topics in This Module

0/7 done