These are the notes for C++ episode 40, the final episode of the C++ course. No new topic: we build a real program with what the course taught. Ravi's notebook of orders is full of mistakes, so we plan a billing system, then build it step by step, letting it break on the way: parallel arrays go out of sync, so we use a struct; we look items up by name with a map and hit the [] trap; we refuse bad orders with exceptions; we save the day to a file; and STL algorithms write the report. At the end there's the complete program in one file. Every program was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the SyntaxPilot compiler's command) and run; outputs are copied from those runs.
The problem: Ravi's notebook
Ravi writes every order by hand: prices, how many samosas are left, every bill. Every evening something is wrong: a total doesn't add up, or he sold poha he didn't have. He asks: can you write me a program?
Plan it before you code it
| # | Ravi needs | C++ we'll use | Episode |
|---|---|---|---|
| 1 | Items with a name, a price and a stock | struct Item |
11 |
| 2 | A menu board, costliest first | vector, sort with a lambda |
21, 27, 30 |
| 3 | Orders by name: chai 3 |
map<string, Item>, cin |
4, 23 |
| 4 | Refuse items we don't sell or don't have | find, throw, try / catch |
31 |
| 5 | Save the day, report the best seller | ofstream, ifstream, accumulate, max_element |
27, 32 |
Rule: data first, then the actions on it.
Step 1: the data
The obvious way: three parallel arrays
Item number i is name[i], price[i] and stock[i]: three arrays linked only by position (parallel arrays). For the board, sort the prices, biggest first:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string name[4] = {"Chai", "Samosa", "Poha", "Lassi"};
int price[4] = {15, 20, 30, 40};
int stock[4] = {100, 40, 25, 30};
sort(price, price + 4, greater<int>()); // costliest first, for the board
for (int i = 0; i < 4; i++)
cout << name[i] << ": Rs " << price[i]
<< " (" << stock[i] << " left)" << endl;
return 0;
}
Output:
Chai: Rs 40 (100 left)
Samosa: Rs 30 (40 left)
Poha: Rs 20 (25 left)
Lassi: Rs 15 (30 left)
Every price is on the wrong item: chai for Rs 40, lassi for Rs 15. sort moved the prices, but the names and stock stayed put. Data that belongs together was living apart.
The fix: a struct, sorted with a lambda
Like a tag tied to each jar, a struct keeps an item's name, price and stock together, so sorting moves the whole item. sort needs to know what "comes first" means for an Item, so we pass a lambda (a small unnamed function, episode 30): a comes first if its price is higher.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Item { // one item, all its data together
string name;
int price;
int stock;
};
int main() {
vector<Item> menu = {{"Chai", 15, 100}, {"Samosa", 20, 40},
{"Poha", 30, 25}, {"Lassi", 40, 30}};
sort(menu.begin(), menu.end(),
[](const Item& a, const Item& b) { return a.price > b.price; });
for (const Item& it : menu)
cout << it.name << ": Rs " << it.price
<< " (" << it.stock << " left)" << endl;
return 0;
}
Output:
Lassi: Rs 40 (30 left)
Poha: Rs 30 (25 left)
Samosa: Rs 20 (40 left)
Chai: Rs 15 (100 left)
Step 2: orders by name, and the [] trap
Customers say names, not index numbers. Finding "chai" in a vector is a loop over everything; a map<string, Item> jumps straight to it (the key is the name, the value is the Item). Orders are read from input until it ends, one per line:
#include <iostream>
#include <string>
#include <map>
using namespace std;
struct Item { string name; int price; int stock; };
map<string, Item> menu = { // name -> its Item
{"chai", {"Chai", 15, 100}}, {"samosa", {"Samosa", 20, 40}},
{"poha", {"Poha", 30, 25}}, {"lassi", {"Lassi", 40, 30}}};
int main() {
string what; int qty, total = 0;
while (cin >> what >> qty) { // one order per line: "chai 3"
Item& it = menu[what]; // look it up by name
total += it.price * qty;
cout << qty << " x " << what << " = Rs " << it.price * qty << endl;
}
cout << "Total: Rs " << total << endl;
cout << "Items on the menu: " << menu.size() << endl;
return 0;
}
Input:
chai 3
samosa 2
coffee 1
Output:
3 x chai = Rs 45
2 x samosa = Rs 40
1 x coffee = Rs 0
Total: Rs 85
Items on the menu: 5
A free coffee, and the menu grew from 4 items to 5. Why? menu[key] never fails: if the key isn't there, it creates it with a default Item (empty name, price 0, stock 0) and returns that. Great for counting (earned[item] += rupees), dangerous for looking things up.
| To look up a key | If it's missing |
|---|---|
m[key] |
inserts a default value, no error |
m.find(key) |
returns m.end(); nothing is added |
m.at(key) |
throws std::out_of_range (message map::at) |
m.count(key) |
returns 0 (C++20: m.contains(key) returns false) |
Step 3: saying no with exceptions
A good helper checks the price list and doesn't invent a price (find). He can't fix the problem himself, so he calls out to the counter (throw); the counter says sorry and serves the next customer (catch), and the stall keeps running. We also refuse orders bigger than the stock:
#include <iostream>
#include <string>
#include <map>
#include <stdexcept>
using namespace std;
struct Item { string name; int price; int stock; };
map<string, Item> menu = { // name -> its Item
{"chai", {"Chai", 15, 100}}, {"samosa", {"Samosa", 20, 40}},
{"poha", {"Poha", 30, 25}}, {"lassi", {"Lassi", 40, 30}}};
Item& findItem(const string& what) {
auto pos = menu.find(what); // find() never adds anything
if (pos == menu.end()) throw runtime_error("no " + what + " on the menu");
return pos->second;
}
int main() {
string what; int qty, total = 0;
while (cin >> what >> qty) {
try {
Item& it = findItem(what);
if (qty > it.stock) // not enough left
throw runtime_error("only " + to_string(it.stock) + " left");
it.stock -= qty; // take them out of stock
total += it.price * qty;
cout << qty << " x " << it.name << " = Rs " << it.price * qty << endl;
} catch (const runtime_error& e) {
cout << "Sorry: " << e.what() << endl; // say sorry, carry on
}
}
cout << "Total: Rs " << total << endl;
cout << "Items on the menu: " << menu.size() << endl;
return 0;
}
Input:
chai 3
samosa 2
coffee 1
poha 30
lassi 1
Output:
3 x Chai = Rs 45
2 x Samosa = Rs 40
Sorry: no coffee on the menu
Sorry: only 25 left
1 x Lassi = Rs 40
Total: Rs 125
Items on the menu: 4
findItemreturns a reference (Item&), soit.stock -= qtychanges the item inside the map, not a copy.runtime_error(from<stdexcept>) carries a message;e.what()gives it back.- The
tryis inside the loop, so one bad order doesn't stop the others. Catch byconstreference. - The menu still has 4 items:
findnever adds anything.
The copy trap: Item vs Item&
findItem returns a reference, but the caller must keep it as a reference. Here sell stores it in a plain Item:
#include <iostream>
#include <string>
#include <map>
#include <stdexcept>
using namespace std;
struct Item { string name; int price; int stock; };
map<string, Item> menu = { // name -> its Item
{"chai", {"Chai", 15, 100}}, {"samosa", {"Samosa", 20, 40}},
{"poha", {"Poha", 30, 25}}, {"lassi", {"Lassi", 40, 30}}};
Item& findItem(const string& what) {
auto pos = menu.find(what);
if (pos == menu.end()) throw runtime_error("no " + what + " on the menu");
return pos->second;
}
void sell(const string& what, int qty) {
Item it = findItem(what); // a copy of the item
if (qty > it.stock) { cout << "Sorry: only " << it.stock << " left" << endl; return; }
it.stock -= qty;
cout << "Sold " << qty << " " << what << endl;
}
int main() {
sell("samosa", 30); // 40 in stock
sell("samosa", 30); // only 10 should be left
cout << "Samosas left: " << findItem("samosa").stock << endl;
return 0;
}
Output:
Sold 30 samosa
Sold 30 samosa
Samosas left: 40
Sixty samosas sold out of forty! Item it = ... makes a copy (a photocopy of the tag); the stock is crossed out on the copy and the item in the map never changes. With Item& it (a reference, episode 10: another name for the item in the map):
#include <iostream>
#include <string>
#include <map>
#include <stdexcept>
using namespace std;
struct Item { string name; int price; int stock; };
map<string, Item> menu = { // name -> its Item
{"chai", {"Chai", 15, 100}}, {"samosa", {"Samosa", 20, 40}},
{"poha", {"Poha", 30, 25}}, {"lassi", {"Lassi", 40, 30}}};
Item& findItem(const string& what) {
auto pos = menu.find(what);
if (pos == menu.end()) throw runtime_error("no " + what + " on the menu");
return pos->second;
}
void sell(const string& what, int qty) {
Item& it = findItem(what); // the item in the map
if (qty > it.stock) { cout << "Sorry: only " << it.stock << " left" << endl; return; }
it.stock -= qty;
cout << "Sold " << qty << " " << what << endl;
}
int main() {
sell("samosa", 30); // 40 in stock
sell("samosa", 30); // only 10 should be left
cout << "Samosas left: " << findItem("samosa").stock << endl;
return 0;
}
Output:
Sold 30 samosa
Sorry: only 10 left
Samosas left: 10
Step 4: saving the day to a file
When the program ends, every variable is gone: they live in memory (RAM), which is cleared. A file stays on the disk. At closing time an ofstream writes each sale; next morning an ifstream reads it back (episode 32). Here earned[what] += rupees is exactly right: a new item starts at 0.
#include <iostream>
#include <fstream>
#include <map>
#include <algorithm>
#include <numeric>
using namespace std;
int main() {
ofstream out("sales.txt"); // closing time: save the day
out << "chai 45\nsamosa 160\npoha 90\nlassi 120\nchai 60\n";
out.close();
ifstream in("sales.txt"); // next morning: read it back
map<string, int> earned;
string what; int rupees;
while (in >> what >> rupees) earned[what] += rupees; // add up per item
int total = accumulate(earned.begin(), earned.end(), 0,
[](int sum, auto& p) { return sum + p.second; });
auto best = max_element(earned.begin(), earned.end(),
[](auto& a, auto& b) { return a.second < b.second; });
for (const auto& [item, rs] : earned) cout << item << ": Rs " << rs << endl;
cout << "Total: Rs " << total << endl;
cout << "Best seller: " << best->first << endl;
return 0;
}
Output:
chai: Rs 105
lassi: Rs 120
poha: Rs 90
samosa: Rs 160
Total: Rs 475
Best seller: samosa
accumulate(begin, end, 0, lambda)(from<numeric>) folds every element into one value; for a map each element is apair, so the lambda addsp.second.max_element(begin, end, lambda)returns an iterator to the biggest element by our rule;best->firstis its key.for (const auto& [item, rs] : earned)is a range-for with structured bindings (episode 33).- Chai appears twice in the file (45 and 60), so it adds up to 105.
- (In the SyntaxPilot compiler each run starts in a fresh folder, so the program writes and reads the file in the same run. On your computer, write in one run and read in the next.)
The complete program
Everything together, with a class Stall that owns the menu and the day's earnings (classes, episode 12), an invalid_argument for a quantity of 0, and ios::app so each day's sales are appended to the file instead of replacing it:
// Ravi's chai stall: the whole capstone program in one file.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <numeric>
#include <stdexcept>
using namespace std;
struct Item {
string name;
int price;
int stock;
};
class Stall {
map<string, Item> menu; // key: the name customers type
map<string, int> earned; // rupees per item today
public:
void add(const string& key, const Item& it) { menu[key] = it; }
void printBoard() const { // costliest first
vector<Item> board;
for (const auto& [key, it] : menu) board.push_back(it);
sort(board.begin(), board.end(),
[](const Item& a, const Item& b) { return a.price > b.price; });
cout << "--- Menu ---\n";
for (const Item& it : board)
cout << it.name << ": Rs " << it.price << " (" << it.stock << " left)\n";
}
Item& findItem(const string& key) {
auto pos = menu.find(key); // find() never adds a key
if (pos == menu.end()) throw runtime_error("no " + key + " on the menu");
return pos->second;
}
int order(const string& key, int qty) { // returns the bill, or throws
if (qty <= 0) throw invalid_argument("quantity must be at least 1");
Item& it = findItem(key);
if (qty > it.stock) throw runtime_error("only " + to_string(it.stock) + " left");
it.stock -= qty;
int bill = it.price * qty;
earned[key] += bill;
return bill;
}
void save(const string& file) const { // append today's sales
ofstream out(file, ios::app);
for (const auto& [key, rs] : earned) out << key << " " << rs << "\n";
}
};
void report(const string& file) {
ifstream in(file);
if (!in) { cout << "Can't open " << file << "\n"; return; }
map<string, int> total;
string key; int rs;
while (in >> key >> rs) total[key] += rs;
if (total.empty()) { cout << "No sales yet\n"; return; }
int sum = accumulate(total.begin(), total.end(), 0,
[](int s, const auto& p) { return s + p.second; });
auto best = max_element(total.begin(), total.end(),
[](const auto& a, const auto& b) { return a.second < b.second; });
cout << "--- Report ---\n";
for (const auto& [k, v] : total) cout << k << ": Rs " << v << "\n";
cout << "Total: Rs " << sum << "\nBest seller: " << best->first << "\n";
}
int main() {
Stall stall;
stall.add("chai", {"Chai", 15, 100});
stall.add("samosa", {"Samosa", 20, 40});
stall.add("poha", {"Poha", 30, 25});
stall.add("lassi", {"Lassi", 40, 30});
stall.printBoard();
cout << "--- Orders ---\n";
string key; int qty, total = 0;
while (cin >> key >> qty) {
try {
int bill = stall.order(key, qty);
total += bill;
cout << qty << " x " << key << " = Rs " << bill << "\n";
} catch (const exception& e) { // runtime_error and invalid_argument
cout << "Sorry: " << e.what() << "\n";
}
}
cout << "Takings: Rs " << total << "\n";
stall.save("sales.txt"); // closing time
report("sales.txt"); // the daily report
return 0;
}
Input:
chai 3
samosa 2
coffee 1
poha 30
lassi 1
chai 4
samosa 0
Output:
--- Menu ---
Lassi: Rs 40 (30 left)
Poha: Rs 30 (25 left)
Samosa: Rs 20 (40 left)
Chai: Rs 15 (100 left)
--- Orders ---
3 x chai = Rs 45
2 x samosa = Rs 40
Sorry: no coffee on the menu
Sorry: only 25 left
1 x lassi = Rs 40
4 x chai = Rs 60
Sorry: quantity must be at least 1
Takings: Rs 185
--- Report ---
chai: Rs 105
lassi: Rs 40
samosa: Rs 40
Total: Rs 185
Best seller: chai
catch (const exception& e) catches both runtime_error and invalid_argument, because both derive from std::exception (inheritance, episode 15).
Common mistakes
| Mistake | What you see | Fix |
|---|---|---|
Parallel arrays + sort(price, price + 4, ...) |
Chai: Rs 40 (only one array moved) |
struct Item, sort the vector<Item> |
Item& it = menu[what]; to look up |
1 x coffee = Rs 0, Items on the menu: 5 |
menu.find(what) or menu.at(what) |
throw with no try / catch |
terminate called after throwing an instance of 'std::runtime_error' what(): no coffee on the menu, then the program aborts |
try { ... } catch (const runtime_error& e) { ... } |
A typo in the file name: ifstream in("sale.txt") |
no error at all, an empty report | if (!in) { cout << "Can't open ..."; return 1; } |
Item it = findItem(what); (no &) |
the stock never goes down: the copy changes, the map doesn't | Item& it = ... |
try around the whole loop |
the first bad order stops all the others | put try inside the loop |
ofstream out("sales.txt") every day |
yesterday's sales are overwritten | ofstream out("sales.txt", ios::app) |
The uncaught exception, run for real:
#include <iostream>
#include <string>
#include <map>
#include <stdexcept>
using namespace std;
struct Item { string name; int price; int stock; };
map<string, Item> menu = { // name -> its Item
{"chai", {"Chai", 15, 100}}, {"samosa", {"Samosa", 20, 40}},
{"poha", {"Poha", 30, 25}}, {"lassi", {"Lassi", 40, 30}}};
Item& findItem(const string& what) {
auto pos = menu.find(what);
if (pos == menu.end()) throw runtime_error("no " + what + " on the menu");
return pos->second;
}
int main() {
cout << findItem("coffee").price << endl; // no try / catch
return 0;
}
Output:
terminate called after throwing an instance of 'std::runtime_error'
what(): no coffee on the menu
Aborted
The file-name check, run for real:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream in("sale.txt"); // typo: the file is sales.txt
if (!in) {
cout << "Can't open sale.txt" << endl;
return 1;
}
return 0;
}
Output:
Can't open sale.txt
Practice: grow the project
- Add 5% GST to every bill.
- Warn when an item's stock falls below 10.
- Save the stock to a file at closing time and load it every morning.
- Turn the menu into a class with its own methods (the complete program above does this; add a
restock(key, n)method).
Solutions
Exercises 1 and 2: multiply by 1.05 (a double, because of the paise), and check the stock after each sale.
#include <iostream>
#include <string>
#include <map>
#include <stdexcept>
using namespace std;
struct Item { string name; int price; int stock; };
map<string, Item> menu = {{"chai", {"Chai", 15, 100}}, {"samosa", {"Samosa", 20, 12}}};
int main() {
string what; int qty;
double total = 0;
while (cin >> what >> qty) {
auto pos = menu.find(what);
if (pos == menu.end() || qty > pos->second.stock) { cout << "Sorry: can't serve " << what << "\n"; continue; }
Item& it = pos->second;
it.stock -= qty;
double bill = it.price * qty * 1.05; // + 5% GST
total += bill;
cout << qty << " x " << it.name << " = Rs " << bill << " (with GST)\n";
if (it.stock < 10) cout << " Warning: only " << it.stock << " " << it.name << " left\n";
}
cout << "Total: Rs " << total << "\n";
return 0;
}
Input:
chai 2
samosa 3
samosa 1
Output:
2 x Chai = Rs 31.5 (with GST)
3 x Samosa = Rs 63 (with GST)
Warning: only 9 Samosa left
1 x Samosa = Rs 21 (with GST)
Warning: only 8 Samosa left
Total: Rs 115.5
Exercise 3: loadStock uses a starting stock when the file doesn't exist yet (the first day), and saveStock writes one line per item.
#include <iostream>
#include <fstream>
#include <string>
#include <map>
using namespace std;
void saveStock(const map<string, int>& stock) {
ofstream out("stock.txt");
for (const auto& [item, n] : stock) out << item << " " << n << "\n";
}
map<string, int> loadStock() {
map<string, int> stock;
ifstream in("stock.txt");
if (!in) return {{"chai", 100}, {"samosa", 40}}; // first day: the starting stock
string item; int n;
while (in >> item >> n) stock[item] = n;
return stock;
}
int main() {
map<string, int> stock = loadStock(); // day 1: no file yet
stock["samosa"] -= 15; // the day's sales
saveStock(stock); // closing time
map<string, int> tomorrow = loadStock(); // day 2: read the file back
for (const auto& [item, n] : tomorrow) cout << item << ": " << n << " left\n";
return 0;
}
Output:
chai: 100 left
samosa: 25 left
Exercise 4: add to class Stall:
void restock(const string& key, int n) {
if (n <= 0) throw invalid_argument("restock at least 1");
findItem(key).stock += n; // throws if the item doesn't exist
}
Quick quiz
map<string, int> stock = {{"chai", 5}};
cout << stock["coffee"] << " ";
cout << stock.size();
Answer
0 2. stock["coffee"] creates the key "coffee" with the value 0, so the map now has 2 keys: the free-coffee bug in three lines. Run:
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> stock = {{"chai", 5}};
cout << stock["coffee"] << " ";
cout << stock.size() << endl;
return 0;
}
Output:
0 2
Interview questions
- Why prefer a struct or class over parallel arrays? The fields of one record stay together, so sorting, inserting or deleting can't separate them, and the code says what the data means.
- What does
map::operator[]do with a missing key? It inserts the key with a value-initialised value (0, empty string...) and returns a reference to it. Usefind,at,countorcontainsto look up without inserting. findvsat?findreturnsend()when the key is missing;atthrowsstd::out_of_range.- When should you throw an exception? When a function can't do its job and the caller is the right place to decide what to do (here, the counter says sorry). Don't use exceptions for normal control flow.
- What happens to an uncaught exception?
std::terminateis called and the program aborts. - Why catch by
constreference? No copy, and no slicing: catchingconst exception&still keeps a derived exception's real type and message. - How do you check that a file opened?
if (!in)(orin.is_open()) right after opening; a failed open is silent otherwise. - Overwrite vs append a file?
ofstream out(name)truncates the file;ofstream out(name, ios::app)adds to the end. - What does
accumulatedo? It folds a range into one value, starting from an initial value, with+or your own function.
Glossary
| Term | Meaning, with an example |
|---|---|
| capstone project | A final project that uses everything from a course together. |
| requirements | What the program must do, written before coding: menu, orders, report. |
| parallel arrays | Several arrays linked only by index: name[i], price[i], stock[i]. |
| out of sync | Parallel arrays no longer match: chai with lassi's price. |
struct |
A type grouping related fields: struct Item { string name; int price; int stock; };. |
| lambda | A small unnamed function written inline: [](const Item& a, const Item& b) { return a.price > b.price; }. |
| comparator | A function that says which of two elements comes first, passed to sort or max_element. |
map<K, V> |
Sorted key → value pairs; find by key in O(log n): "chai" → its Item. |
| key / value | The name you look up / what you get back. |
operator[] on a map |
Returns the value for a key, creating it if missing. |
find() |
Looks up a key; returns end() if missing, never inserts. |
| iterator | A position in a container; pos->second is the value at that position in a map. |
reference (Item&) |
Another name for an existing object: changing it changes the original. |
| exception | An object thrown to report that something went wrong. |
throw |
Raises an exception: throw runtime_error("no coffee on the menu");. |
try / catch |
Run code that may throw / handle the exception and continue. |
runtime_error / invalid_argument |
Standard exception types from <stdexcept>, both derived from std::exception. |
what() |
Returns an exception's message. |
terminate |
What happens to an uncaught exception: the program aborts. |
| RAM (memory) | Where variables live while the program runs; cleared when it ends. |
| file stream | ofstream writes a file, ifstream reads one (<fstream>). |
ios::app |
Open a file for appending instead of overwriting. |
accumulate |
Folds a range into one value (<numeric>): the day's total. |
max_element |
An iterator to the largest element by a comparator (<algorithm>): the best seller. |
| structured bindings | auto& [item, rs] = pair; unpacks a pair into named variables. |
| GST | Goods and Services Tax, added to Indian bills (5% on a restaurant bill like Ravi's). |
Summary
- Plan first: data, then the actions on it.
- Keep related data together in a struct (or class); parallel arrays drift apart.
sortwith a lambda orders structs by any field.- A map finds items by name; never look things up with
[], usefindorat. - Throw when you can't go on; catch where you can recover (inside the loop).
- Files keep data after the program ends:
ofstream(withios::appto append),ifstream, and always checkif (!in). accumulateandmax_elementwrite the report.- That's the C++ course: from
coutto a real project. Next on the channel: C++ coding questions.