Introduction
E-commerce logic is full of rules: you can't buy more than is in stock, coupons have conditions, tax applies after discounts. This project puts those rules in a Cart class backed by std::map, and prints an itemised receipt like a real till.
Problem statement
Objectives
- Encapsulate business rules in a class
- Use std::map for a catalogue and for cart quantities
- Hold a reference to shared data (the catalogue) inside an object
- Format money and tables with <iomanip>
Features
- Stock-aware add (shows how many more are available)
- Partial or full removal of an item
- Two coupon types with eligibility rules
- Receipts with tax rounded to the nearest cent; stock updated after checkout
Concepts demonstrated
- Classes
- std::map
- References as members
- Business rules
- Integer arithmetic for money
System architecture
The catalogue is a std::map<std::string, Product> created in main. Cart keeps a reference to it plus its own map<code, quantity> and the active coupon. add checks the code exists and that cart quantity plus the new quantity doesn't exceed stock. subtotal, discount and the tax calculation are separate functions so each rule is easy to read. checkout subtracts quantities from the catalogue's stock and clears the cart. The command loop in main only parses input and prints the messages returned by Cart.
Folder structure
Complete source code
Makefile
What each file does
- src/main.cpp
Product,money, theCartclass (add/remove/coupons/totals/receipt/checkout) and the command loop.- Makefile
- Build automation:
makebuilds./app,make testruns the sample session and compares it with the expected output,make cleanremoves build files.
How to run it
Build
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
catalog add P01 4 add P04 5 add P04 2 add P09 1 add P05 cart coupon WELCOME coupon SAVE10 remove P01 1 checkout add P06 1 coupon FLAT5 checkout catalog quit
Testing
- Compare the scripted session with
tests/expected-output.txt. - Receipt 1: subtotal $69.20, SAVE10 discount $6.92, tax 8% of $62.28 = $4.98, total $67.26.
- Receipt 2: FLAT5 is not applied because $39.99 is below $40.
- After both orders the catalogue shows reduced stock (Notebook 47, Headphones 1, Backpack 4).
Common errors
std::out_of_range from map::at
Only call catalog_.at(code) for codes that are known to exist; add checks with find first.
Total is off by one cent
Round tax once, at the end: (amount * 8 + 50) / 100 rounds to the nearest cent in integer arithmetic.
Possible improvements
- Load the catalogue from a CSV file
- Support multiple coupons with different priorities
- Save receipts to numbered text files
Additional challenges
- 1Add a 'buy 2 get 1 free' offer on one product.
- 2Make the tax rate depend on the product category.
- 3Add a
restock <code> <qty>admin command.
Built and tested it yourself? Mark it to update your dashboard.