Aral Code

The Standard Library Lesson 17 of 17

C++ Final Project — Store Inventory System

Build a complete C++ inventory system with a Product class, vector and map, a menu, input validation, sorting with lambdas, low-stock alerts and CSV saving and loading.

Let's combine classes, vectors, maps, algorithms, files and exceptions into one real program: an inventory system for a small store. It tracks products, records sales, warns about low stock, and saves everything to a CSV file you can open in Excel.

Features

  1. List products sorted by name.
  2. Add a product, or restock an existing one.
  3. Record a sale, refusing to sell more than the stock.
  4. Show low-stock items and the total inventory value.
  5. Save to and load from inventory.csv.

The code

#include <algorithm>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;

class Product {
    string name;
    double price;
    int stock;
public:
    Product(string n, double p, int s) : name(n), price(p), stock(s) {
        if (p < 0 || s < 0) throw invalid_argument("price and stock can't be negative");
    }
    const string &getName() const { return name; }
    double getPrice() const { return price; }
    int getStock() const { return stock; }
    double value() const { return price * stock; }

    void restock(int qty) { stock += qty; }
    void sell(int qty) {
        if (qty <= 0) throw invalid_argument("quantity must be positive");
        if (qty > stock) throw runtime_error("only " + to_string(stock) + " left");
        stock -= qty;
    }
};

class Inventory {
    vector<Product> items;
    map<string, size_t> index;          // name -> position in items
public:
    void add(const Product &p) {
        auto it = index.find(p.getName());
        if (it != index.end()) {
            items[it->second].restock(p.getStock());
        } else {
            index[p.getName()] = items.size();
            items.push_back(p);
        }
    }
    Product &find(const string &name) {
        auto it = index.find(name);
        if (it == index.end()) throw runtime_error("no product named " + name);
        return items[it->second];
    }
    void list() const {
        vector<const Product *> sorted;
        for (const auto &p : items) sorted.push_back(&p);
        sort(sorted.begin(), sorted.end(),
             [](const Product *a, const Product *b) { return a->getName() < b->getName(); });
        cout << left << setw(20) << "PRODUCT" << right << setw(9) << "PRICE" << setw(7) << "STOCK" << "\n";
        for (const Product *p : sorted) {
            cout << left << setw(20) << p->getName() << right << fixed << setprecision(2)
                 << setw(9) << p->getPrice() << setw(7) << p->getStock()
                 << (p->getStock() < 10 ? "  LOW" : "") << "\n";
        }
    }
    double totalValue() const {
        double total = 0;
        for (const auto &p : items) total += p.value();
        return total;
    }
    void save(const string &file) const {
        ofstream out(file);
        for (const auto &p : items)
            out << p.getName() << ',' << p.getPrice() << ',' << p.getStock() << '\n';
    }
    void load(const string &file) {
        ifstream in(file);
        string line;
        while (getline(in, line)) {
            stringstream ss(line);
            string name, price, stock;
            if (getline(ss, name, ',') && getline(ss, price, ',') && getline(ss, stock))
                add(Product(name, stod(price), stoi(stock)));
        }
    }
};

int readInt(const string &prompt) {
    int n;
    while (true) {
        cout << prompt;
        if (cin >> n) { cin.ignore(numeric_limits<streamsize>::max(), '\n'); return n; }
        cout << "Please enter a whole number.\n";
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
}

string readLine(const string &prompt) {
    string s;
    cout << prompt;
    getline(cin, s);
    return s;
}

int main() {
    Inventory inv;
    inv.load("inventory.csv");
    while (true) {
        cout << "\n[1] List  [2] Add/restock  [3] Sell  [4] Report  [0] Save & exit\n";
        int choice = readInt("Choice: ");
        try {
            if (choice == 1) {
                inv.list();
            } else if (choice == 2) {
                string name = readLine("Name: ");
                int qty = readInt("Quantity: ");
                cout << "Price: ";
                double price;
                cin >> price;
                cin.ignore(numeric_limits<streamsize>::max(), '\n');
                inv.add(Product(name, price, qty));
                cout << "Done.\n";
            } else if (choice == 3) {
                Product &p = inv.find(readLine("Product: "));
                int qty = readInt("Quantity: ");
                p.sell(qty);
                cout << fixed << setprecision(2) << "Sold. Amount due: P" << qty * p.getPrice() << "\n";
            } else if (choice == 4) {
                cout << fixed << setprecision(2) << "Total inventory value: P" << inv.totalValue() << "\n";
            } else if (choice == 0) {
                inv.save("inventory.csv");
                cout << "Saved. Goodbye!\n";
                break;
            }
        } catch (const exception &e) {
            cout << "Error: " << e.what() << "\n";
        }
    }
    return 0;
}

Sample run

Output

[1] List  [2] Add/restock  [3] Sell  [4] Report  [0] Save & exit
Choice: 2
Name: Kape 3-in-1
Quantity: 50
Price: 8
Done.

[1] List  [2] Add/restock  [3] Sell  [4] Report  [0] Save & exit
Choice: 2
Name: Sardinas
Quantity: 12
Price: 24
Done.

[1] List  [2] Add/restock  [3] Sell  [4] Report  [0] Save & exit
Choice: 3
Product: Sardinas
Quantity: 5
Sold. Amount due: P120.00

[1] List  [2] Add/restock  [3] Sell  [4] Report  [0] Save & exit
Choice: 3
Product: Sardinas
Quantity: 20
Error: only 7 left

[1] List  [2] Add/restock  [3] Sell  [4] Report  [0] Save & exit
Choice: 1
PRODUCT                 PRICE  STOCK
Kape 3-in-1              8.00     50
Sardinas                24.00      7  LOW

[1] List  [2] Add/restock  [3] Sell  [4] Report  [0] Save & exit
Choice: 0
Saved. Goodbye!

Design notes

PartWhy it's done this way
Product throws on bad dataAn invalid product can never exist
Inventory wraps a vector + mapKeeps insertion order and gives fast lookup by name
find returns Product &The caller can change the real product (sell it)
list sorts pointersShows items alphabetically without reordering the vector
One try around each menu actionAny error is shown and the program keeps running
CSV fileOpens directly in Excel or Google Sheets

Challenges

  1. Add a "delete product" option (remember to rebuild the index map).
  2. Record each sale with the date in sales.csv, and add a daily sales report.
  3. Validate the price input with a readDouble helper, like readInt.
  4. Make Perishable a subclass of Product with an expiry date, and list items expiring soon.
  5. Search products by partial name, ignoring capital letters.

What's next?

Congratulations on finishing the C++ course! 🎉 Possible next steps:

  • Competitive programming: practice STL-based problem solving on contest sites.
  • Game development: try a library like SFML or raylib, or Unreal Engine.
  • Arduino and robotics: C++ runs directly on microcontrollers.
  • C#: similar syntax, used with Unity for games.

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. Why does Inventory keep both a vector and a map?
2. Why does find return Product & instead of Product?
3. What happens when selling more than the stock?
4. Why is the inventory saved as CSV?

By Sir Reyel · Last updated 2026-12-04