C++ · Module 19 · Lesson 41 min read

Project: Expense Tracker with Budgets

Features checklist

  1. Record income and expenses (date, category, amount, note)
  2. Category budgets with alerts at 80% and 100%
  3. Monthly report: totals per category, budget usage bars, top expenses
  4. Savings rate = (income − expenses) / income
  5. Recurring transactions (rent, subscriptions) added each month
  6. Undo the last transaction (a stack)
  7. Commands read from std::cin

Design

c
struct Date { int y, m, d; auto operator<=>(...) = default; };
class Transaction (abstract): virtual long long signed_amount() const = 0;
├── Income
└── Expense  (category)
class Tracker {
    std::vector<std::unique_ptr<Transaction>> txs_;
    std::map<std::string, long long> budgets_;
    std::stack<std::size_t> undo_;           // or just pop_back
    std::function<void(std::string)> on_alert_;   // callback
};

Concepts practised

Polymorphism with smart pointers, std::map aggregation, <=> for dates, ranges/algorithms (std::ranges::sort, partial_sort), std::function callbacks for alerts, std::format reports, text bar charts.

Business rules

  • Amounts in paisa; reject zero or negative values
  • Alerts fire once per category per month when crossing 80% and 100%
  • Reports only include the chosen month

Extensions

CSV import from a bank statement (Unit 16), multiple wallets (cash, bank, eSewa), goals with progress, a yearly summary, persistence with serialization.

Example

C++
#include <algorithm>
#include <compare>
#include <format>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <set>
#include <sstream>
#include <string>
#include <vector>

struct Date {
    int y, m, d;
    auto operator<=>(const Date&) const = default;
};

std::string rs(long long paisa) { return std::format("{}", paisa / 100); }

class Transaction {
public:
    Transaction(Date date, long long amount, std::string note) : date_(date), amount_(amount), note_(std::move(note)) {
        if (amount_ <= 0) throw std::invalid_argument("amount must be positive");
    }
    virtual ~Transaction() = default;
    virtual long long signed_amount() const = 0;
    virtual std::string category() const = 0;
    const Date& date() const { return date_; }
    long long amount() const { return amount_; }
    const std::string& note() const { return note_; }
private:
    Date date_;
    long long amount_;
    std::string note_;
};

class Income : public Transaction {
public:
    using Transaction::Transaction;
    long long signed_amount() const override { return amount(); }
    std::string category() const override { return "Income"; }
};

class Expense : public Transaction {
public:
    Expense(Date date, long long amount, std::string category, std::string note)
        : Transaction(date, amount, std::move(note)), category_(std::move(category)) {}
    long long signed_amount() const override { return -amount(); }
    std::string category() const override { return category_; }
private:
    std::string category_;
};

class Tracker {
public:
    using AlertHandler = std::function<void(const std::string&)>;
    void on_alert(AlertHandler h) { alert_ = std::move(h); }
    void set_budget(const std::string& cat, long long amount) { budgets_[cat] = amount; }

    void add(std::unique_ptr<Transaction> t) {
        const Transaction& ref = *t;
        txs_.push_back(std::move(t));
        if (ref.signed_amount() < 0) check_budget(ref.category(), ref.date());
    }
    bool undo() {
        if (txs_.empty()) return false;
        std::cout << "  undo: " << txs_.back()->note() << '\n';
        txs_.pop_back();
        return true;
    }
    void report(int y, int m) const {
        long long income = 0, spent = 0;
        std::map<std::string, long long> by_cat;
        std::vector<const Transaction*> expenses;
        for (const auto& t : txs_) {
            if (t->date().y != y || t->date().m != m) continue;
            if (t->signed_amount() > 0) income += t->amount();
            else { spent += t->amount(); by_cat[t->category()] += t->amount(); expenses.push_back(t.get()); }
        }
        std::cout << std::format("== Report {}-{:02} ==\nincome Rs. {}, expenses Rs. {}, saved Rs. {} ({:.0f}%)\n",
                                 y, m, rs(income), rs(spent), rs(income - spent), income ? 100.0 * (income - spent) / income : 0.0);
        for (const auto& [cat, amt] : by_cat) {
            auto b = budgets_.find(cat);
            if (b == budgets_.end()) { std::cout << std::format("  {:<9}{:>7}\n", cat, rs(amt)); continue; }
            int pct = static_cast<int>(100 * amt / b->second);
            std::cout << std::format("  {:<9}{:>7} / {:<6} {:<10} {}%\n", cat, rs(amt), rs(b->second),
                                     std::string(std::min(pct, 100) / 10, '#'), pct);
        }
        std::ranges::partial_sort(expenses, expenses.begin() + std::min<std::size_t>(3, expenses.size()),
                                  std::ranges::greater{}, &Transaction::amount);
        std::cout << "  top expenses:";
        for (std::size_t i = 0; i < std::min<std::size_t>(3, expenses.size()); ++i)
            std::cout << ' ' << expenses[i]->note() << " (" << rs(expenses[i]->amount()) << ")";
        std::cout << '\n';
    }
private:
    void check_budget(const std::string& cat, const Date& date) {
        auto b = budgets_.find(cat);
        if (b == budgets_.end()) return;
        long long spent = 0;
        for (const auto& t : txs_)
            if (t->signed_amount() < 0 && t->category() == cat && t->date().y == date.y && t->date().m == date.m)
                spent += t->amount();
        for (int level : { 100, 80 }) {
            if (spent * 100 < b->second * level) continue;
            if (alerted_.insert(std::format("{}-{}-{}-{}", cat, date.y, date.m, level)).second && alert_)
                alert_(std::format("{} budget {}% reached (Rs. {} of {})", cat, level, rs(spent), rs(b->second)));
            break;                                   // only the highest level reached matters
        }
    }
    std::vector<std::unique_ptr<Transaction>> txs_;
    std::map<std::string, long long> budgets_;
    std::set<std::string> alerted_;
    AlertHandler alert_;
};

int main() {
    Tracker t;
    t.on_alert([](const std::string& msg) { std::cout << "  ALERT: " << msg << '\n'; });
    t.set_budget("Food", 800000);
    t.set_budget("Fun", 300000);
    t.set_budget("Rent", 1500000);

    std::string line;
    while (std::getline(std::cin, line)) {
        std::istringstream in(line);
        std::string kind, cat, note;
        Date d{};
        double rupees;
        char dash;
        in >> kind;
        if (kind == "undo") { t.undo(); continue; }
        if (kind == "report") { in >> d.y >> dash >> d.m; t.report(d.y, d.m); continue; }
        in >> d.y >> dash >> d.m >> dash >> d.d >> rupees;
        if (kind == "exp") in >> cat;
        std::getline(in >> std::ws, note);
        try {
            long long p = static_cast<long long>(rupees * 100);
            if (kind == "inc") t.add(std::make_unique<Income>(d, p, note));
            else t.add(std::make_unique<Expense>(d, p, cat, note));
        } catch (const std::exception& e) {
            std::cout << "  rejected '" << note << "': " << e.what() << '\n';
        }
    }
    return 0;
}

/* Output:
  ALERT: Rent budget 100% reached (Rs. 15000 of 15000)
  ALERT: Food budget 80% reached (Rs. 6700 of 8000)
  rejected 'free sample': amount must be positive
  ALERT: Fun budget 100% reached (Rs. 3200 of 3000)
  undo: impulse gadget
  ALERT: Food budget 100% reached (Rs. 8500 of 8000)
== Report 2026-11 ==
income Rs. 55000, expenses Rs. 28000, saved Rs. 27000 (49%)
  Food        8500 / 8000   ########## 106%
  Fun         3200 / 3000   ########## 106%
  Rent       15000 / 15000  ########## 100%
  Travel      1300
  top expenses: flat rent (15000) groceries (4500) concert (3200)
== Report 2026-10 ==
income Rs. 50000, expenses Rs. 1200, saved Rs. 48800 (98%)
  Food        1200 / 8000   #          15%
  top expenses: groceries (1200)
*/