Final project: a command-line expense tracker
Course contents (20 lessons)
- Getting started
- Setting up a C++ compiler and writing your first program
- Variables, types and reading input
- Control flow, functions and indirection
- Control flow: if, switch and loops
- Functions: parameters, return values and overloading
- References and pointers
- Working with data
- Arrays and std::vector
- Working with std::string and string_view
- Classes and object-oriented design
- Structs and classes: your own types
- Constructors, destructors and RAII
- Operator overloading
- Inheritance and virtual functions
- Generic code and the STL
- Templates: writing generic code
- The STL: containers and iterators
- Algorithms and lambdas
- Ownership, moves and errors
- Smart pointers and ownership
- Move semantics and perfect forwarding basics
- Error handling: exceptions, optional and expected
- Modern C++ and a real project
- Modern C++: ranges, concepts and std::format
- Building projects with CMake
- 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 inadd, 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, usingeraseon the vector and checking that the index is valid. - Add dates. Store a
std::chrono::year_month_day(C++20), or just a string inYYYY-MM-DDform, and add amonth <YYYY-MM>command that filters withstd::copy_if.
Try it yourself
- Type the program in rather than pasting it, compile with warnings on, and fix anything your compiler reports.
- Run it, add five expenses, quit, and open
expenses.csvin a text editor. Restart and confirm the data comes back. - Complete two items from the "next" list, and commit the finished project to a repository.
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