Tutorials / C++: From Basics to Modern C++ / Final project: a command-line expense tracker

Final project: a command-line expense tracker

22 min read cpp
Course contents (20 lessons)
  1. Getting started
  2. Setting up a C++ compiler and writing your first program
  3. Variables, types and reading input
  4. Control flow, functions and indirection
  5. Control flow: if, switch and loops
  6. Functions: parameters, return values and overloading
  7. References and pointers
  8. Working with data
  9. Arrays and std::vector
  10. Working with std::string and string_view
  11. Classes and object-oriented design
  12. Structs and classes: your own types
  13. Constructors, destructors and RAII
  14. Operator overloading
  15. Inheritance and virtual functions
  16. Generic code and the STL
  17. Templates: writing generic code
  18. The STL: containers and iterators
  19. Algorithms and lambdas
  20. Ownership, moves and errors
  21. Smart pointers and ownership
  22. Move semantics and perfect forwarding basics
  23. Error handling: exceptions, optional and expected
  24. Modern C++ and a real project
  25. Modern C++: ranges, concepts and std::format
  26. Building projects with CMake
  27. Final project: a command-line expense tracker

What we are building

This project pulls the course together. The program is an interactive expense tracker. You type commands at a prompt, and it stores entries in a file so the data survives between runs. It uses structs and classes, a vector and a map, streams, exceptions, and a CMake build. It is about 120 lines, which is small enough to read in one sitting.

commands: add <category> <amount> <note>, list, summary, quit
> add food 12.50 lunch with the team
added
> add transport 4 bus ticket
added
> summary
food           12.50
transport       4.00
total          16.50
> quit

Design first

Before typing, decide where each responsibility lives. A short plan saves rewriting.

  • Expense: a plain struct with a category, an amount and a note.
  • ExpenseBook: a class that owns a vector of expenses. It validates input in add, answers questions (total, byCategory) and can save and load itself.
  • main: reads commands, calls the book, prints results, and catches errors so one bad command does not end the program.

The book never prints and never reads the keyboard. Keeping input and output out of the data class makes it testable, and you could put a GUI or a web page on top later without touching it.

The code

// src/main.cpp
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>

struct Expense {
    std::string category;
    double amount{};
    std::string note;
};

class ExpenseBook {
public:
    void add(Expense e) {
        if (e.amount <= 0) throw std::invalid_argument("amount must be positive");
        if (e.category.empty()) throw std::invalid_argument("category is required");
        items_.push_back(std::move(e));
    }

    double total() const {
        double sum = 0;
        for (const auto& e : items_) sum += e.amount;
        return sum;
    }

    std::map<std::string, double> byCategory() const {
        std::map<std::string, double> result;
        for (const auto& e : items_) result[e.category] += e.amount;
        return result;
    }

    const std::vector<Expense>& items() const { return items_; }

    void save(const std::string& path) const {
        std::ofstream out{path};
        if (!out) throw std::runtime_error("cannot write " + path);
        for (const auto& e : items_) {
            out << e.category << ',' << e.amount << ',' << e.note << '\n';
        }
    }

    void load(const std::string& path) {
        std::ifstream in{path};
        if (!in) return;                       // first run: no file yet
        std::string line;
        while (std::getline(in, line)) {
            std::istringstream row{line};
            Expense e;
            std::string amountText;
            if (std::getline(row, e.category, ',') && std::getline(row, amountText, ',')) {
                std::getline(row, e.note);
                e.amount = std::stod(amountText);   // throws on a damaged line
                items_.push_back(std::move(e));
            }
        }
    }

private:
    std::vector<Expense> items_;
};

void printList(const ExpenseBook& book) {
    std::cout << std::fixed << std::setprecision(2);
    int n = 1;
    for (const auto& e : book.items()) {
        std::cout << std::setw(3) << n++ << "  "
                  << std::left << std::setw(12) << e.category << std::right
                  << std::setw(10) << e.amount << "  " << e.note << "\n";
    }
}

void printSummary(const ExpenseBook& book) {
    std::cout << std::fixed << std::setprecision(2);
    for (const auto& [category, sum] : book.byCategory()) {
        std::cout << std::left << std::setw(12) << category << std::right
                  << std::setw(10) << sum << "\n";
    }
    std::cout << std::left << std::setw(12) << "total" << std::right
              << std::setw(10) << book.total() << "\n";
}

int main() {
    const std::string file = "expenses.csv";
    ExpenseBook book;

    try {
        book.load(file);
    } catch (const std::exception& ex) {
        std::cerr << "could not read " << file << ": " << ex.what() << "\n";
    }

    std::cout << "commands: add <category> <amount> <note>, list, summary, quit\n";
    std::string line;
    while (std::cout << "> " && std::getline(std::cin, line)) {
        std::istringstream in{line};
        std::string command;
        in >> command;
        try {
            if (command == "add") {
                Expense e;
                if (!(in >> e.category >> e.amount)) {
                    throw std::invalid_argument("usage: add <category> <amount> <note>");
                }
                std::getline(in >> std::ws, e.note);
                book.add(std::move(e));
                std::cout << "added\n";
            } else if (command == "list") {
                printList(book);
            } else if (command == "summary") {
                printSummary(book);
            } else if (command == "quit") {
                break;
            } else if (!command.empty()) {
                std::cout << "unknown command: " << command << "\n";
            }
        } catch (const std::exception& ex) {
            std::cout << "error: " << ex.what() << "\n";
        }
    }

    try {
        book.save(file);
    } catch (const std::exception& ex) {
        std::cerr << "could not save: " << ex.what() << "\n";
        return 1;
    }
    return 0;
}

Walking through the important parts

Validation lives in the class. add throws std::invalid_argument for a zero amount or a missing category. The main loop catches every std::exception inside the loop body, prints the message, and continues. A typo costs the user one line, not their session.

The command line is parsed with a string stream. Each line becomes an istringstream. The first word is the command. For add, the stream extracts a category and a number, then std::getline(in >> std::ws, e.note) skips the spaces and takes the rest of the line as the note, so notes can contain spaces.

The map gives sorted summaries for free. result[e.category] += e.amount creates a zero entry on first use and adds to it. Iterating a std::map visits keys in alphabetical order, which is what we want.

The CMake file

cmake_minimum_required(VERSION 3.20)
project(ExpenseTracker LANGUAGES CXX)

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

add_executable(tracker src/main.cpp)

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

Build with cmake -S . -B build and cmake --build build, then run the program from the folder where you want expenses.csv to appear.

Where to take it next

Treat these as the real exercise. Pick at least two.

  • Add a delete <number> command, using erase on the vector and checking that the index is valid.
  • Add dates. Store a std::chrono::year_month_day (C++20), or just a string in YYYY-MM-DD form, and add a month <YYYY-MM> command that filters with std::copy_if.

Try it yourself

  1. Type the program in rather than pasting it, compile with warnings on, and fix anything your compiler reports.
  2. Run it, add five expenses, quit, and open expenses.csv in a text editor. Restart and confirm the data comes back.
  3. Complete two items from the "next" list, and commit the finished project to a repository.
cpp
commands: add <category> <amount> <note>, list, summary, quit
> add food 12.50 lunch with the team
added
> add transport 4 bus ticket
added
> summary
food           12.50
transport       4.00
total          16.50
> quit

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account