C++ Project with Source Code: Online Grocery Store
C++ is not the best language for web development, but you can build a console program that works like an online grocery store: list products with prices and stock, add items to a cart, check out with a customer balance, print a receipt and save every order to a file. Read the code, try the live demo, then add discounts and customer accounts.
How the C++ Online Grocery Store Works
The program follows four steps. Each step is one section of the code below.
- Step 1: Define the products. A
Productstruct holds the name, price and stock, and astd::vectorholds the list. - Step 2: Build the user interface. A menu loop with a
switchlets the customer view products and add or remove cart items. Every input is validated. - Step 3: Implement payment. Checkout adds up the order, deducts it from the customer balance and prints a receipt.
- Step 4: Store the order. The receipt is appended to
orders.txtwith file handling.
break, and checkout() called a getTotal() function that was never written. Payment was a TODO, nothing was saved, and a wrong product number or a negative quantity crashed the program. Items could not be removed, and adding the same product twice created two cart lines. All of that is fixed. The original also said to encrypt customer data. This version avoids the problem by never collecting card numbers: payment uses a simple customer balance, and only the order and receipt are saved.Step 1: Helpers, Products and the Store
Start with the includes, two input helpers and the data structures. readInt() keeps asking until the number is in range, and readLine() refuses empty text. A CartItem stores the index of the product and the quantity, so the price always comes from the product list. The Store struct keeps everything in one place and is passed to the functions.
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <string>
#include <vector>
// Read a non-empty line of text
std::string readLine(const std::string& prompt) {
std::string line;
do {
std::cout << prompt;
if (!std::getline(std::cin, line)) std::exit(0); // input closed
} while (line.empty());
return line;
}
// Read an integer between min and max
int readInt(const std::string& prompt, int min, int max) {
int value;
while (true) {
std::cout << prompt;
if (std::cin >> value && value >= min && value <= max) {
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return value;
}
if (std::cin.eof()) std::exit(0);
std::cout << "Please enter a number between " << min << " and " << max << ".\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
struct Product {
std::string name;
double price;
int quantity; // stock
};
struct CartItem {
std::size_t productIndex;
int quantity;
};
struct Store {
std::vector<Product> products;
std::vector<CartItem> cart;
std::string customer;
double balance;
int orderNumber;
};
Store createStore(const std::string& customer, double balance) {
Store store;
store.products = {
{"Apple", 2.99, 20},
{"Orange", 3.99, 15},
{"Banana", 1.99, 25},
{"Grapes", 5.99, 10},
{"Milk", 2.49, 30},
{"Eggs", 1.99, 40},
{"Bread", 3.49, 25}
};
store.customer = customer;
store.balance = balance;
store.orderNumber = 1;
return store;
}Step 2: Show Products and Manage the Cart
addToCart() checks the stock, merges the item into an existing cart line if there is one, and reduces the stock. removeFromCart() does the reverse and puts the stock back. cartTotal() is the helper that the original code was missing.
double cartTotal(const Store& store) {
double total = 0;
for (const auto& item : store.cart) {
total += store.products[item.productIndex].price * item.quantity;
}
return total;
}
void displayProducts(const Store& store) {
std::cout << "Welcome to our online grocery store!\n";
std::cout << "-------------------------------------\n";
std::cout << "Available Products:\n";
for (std::size_t i = 0; i < store.products.size(); i++) {
const Product& p = store.products[i];
std::cout << i + 1 << ". " << p.name << " - $" << p.price << " (";
if (p.quantity > 0) std::cout << p.quantity << " in stock)\n";
else std::cout << "out of stock)\n";
}
}
void addToCart(Store& store, int number, int quantity) {
std::size_t index = number - 1; // the menu starts at 1
Product& product = store.products[index];
if (quantity > product.quantity) {
std::cout << "Sorry, we don't have enough items in stock.\n";
return;
}
bool found = false;
for (auto& item : store.cart) {
if (item.productIndex == index) { // same product: add to the existing line
item.quantity += quantity;
found = true;
break;
}
}
if (!found) store.cart.push_back({index, quantity});
product.quantity -= quantity;
std::cout << "Added " << quantity << " " << product.name << " to your cart.\n";
}
void displayCart(const Store& store) {
if (store.cart.empty()) {
std::cout << "Your cart is empty.\n";
return;
}
std::cout << "Your cart:\n";
for (std::size_t i = 0; i < store.cart.size(); i++) {
const CartItem& item = store.cart[i];
const Product& p = store.products[item.productIndex];
std::cout << i + 1 << ". " << p.name << " - $" << p.price << " x " << item.quantity
<< " = $" << p.price * item.quantity << "\n";
}
std::cout << "Total: $" << cartTotal(store) << std::endl;
}
void removeFromCart(Store& store, int number) {
CartItem item = store.cart[number - 1];
store.products[item.productIndex].quantity += item.quantity; // put the stock back
store.cart.erase(store.cart.begin() + (number - 1));
std::cout << "Item removed from your cart.\n";
}Step 3: Checkout, Receipt and Order File
printReceipt() takes any output stream, so the same function prints to the screen with std::cout and writes to orders.txt with std::ofstream. checkout() refuses the order if the balance is too low, otherwise it deducts the total, prints the receipt, saves it and clears the cart.
void printReceipt(std::ostream& out, const Store& store, double total) {
out << std::fixed << std::setprecision(2);
out << "----- RECEIPT #" << store.orderNumber << " -----\n";
out << "Customer: " << store.customer << "\n";
for (const auto& item : store.cart) {
const Product& p = store.products[item.productIndex];
out << p.name << " x" << item.quantity << " $" << p.price * item.quantity << "\n";
}
out << "Total: $" << total << "\n";
out << "Balance after payment: $" << store.balance << "\n";
out << "-------------------------\n";
}
void saveOrder(const Store& store, double total) {
std::ofstream file("orders.txt", std::ios::app); // append to the end
if (!file) {
std::cout << "Warning: the order could not be saved.\n";
return;
}
printReceipt(file, store, total);
}
void checkout(Store& store) {
if (store.cart.empty()) {
std::cout << "Your cart is empty.\n";
return;
}
double total = cartTotal(store);
if (total > store.balance) {
std::cout << "Not enough balance. Total: $" << total << ", balance: $" << store.balance
<< ". Add funds or remove items.\n";
return;
}
store.balance -= total;
printReceipt(std::cout, store, total);
saveOrder(store, total);
store.cart.clear();
store.orderNumber++;
std::cout << "Thank you for shopping with us!\n";
}
void addFunds(Store& store, int dollars) {
store.balance += dollars;
std::cout << "New balance: $" << store.balance << "\n";
}Step 4: The Menu and main()
The menu is a loop with a switch, as in the original, but every number the user types goes through readInt(), so a wrong product number or a negative quantity cannot crash the program. Compile with g++ -std=c++11 main.cpp -o grocery and run ./grocery.
int main() {
std::cout << std::fixed << std::setprecision(2);
std::string name = readLine("Enter your name: ");
Store store = createStore(name, 50.00); // every customer starts with $50
int choice;
do {
std::cout << "\nBalance: $" << store.balance << "\n"
<< "1. Display Products\n2. Add to Cart\n3. View Cart\n"
<< "4. Remove from Cart\n5. Checkout\n6. Add Funds\n0. Exit\n";
choice = readInt("Enter your choice: ", 0, 6);
switch (choice) {
case 1:
displayProducts(store);
break;
case 2: {
displayProducts(store);
int number = readInt("Enter the product number: ", 1, static_cast<int>(store.products.size()));
int quantity = readInt("Enter the quantity (1-100): ", 1, 100);
addToCart(store, number, quantity);
break;
}
case 3:
displayCart(store);
break;
case 4:
if (store.cart.empty()) {
std::cout << "Your cart is empty.\n";
} else {
displayCart(store);
removeFromCart(store, readInt("Enter the item number to remove: ", 1,
static_cast<int>(store.cart.size())));
}
break;
case 5:
checkout(store);
break;
case 6:
addFunds(store, readInt("Dollars to add (1-500): ", 1, 500));
break;
}
} while (choice != 0);
std::cout << "Goodbye, " << store.customer << "!\n";
return 0;
}Live Demo: Shop in Your Browser
This demo follows the same rules as the C++ code: stock checks, merged cart lines, stock returned on removal, a balance check at checkout and a receipt. Prices are stored in cents so the totals are exact. Data lives in memory, so a refresh resets it.
Products
| Product | Price | In stock | Qty |
|---|
Your cart
| Item | Price | Qty | Subtotal |
|---|
Ideas to Make the Project Bigger
The original post suggested discounts, promotions and customer accounts. Here is how to add them. Try each one yourself first.
1. A discount on big orders
Give 10% off orders of $20 or more. Add a function, then use it in checkout() and print the discount on the receipt.
double discountFor(double subtotal) {
return subtotal >= 20.0 ? subtotal * 0.10 : 0.0; // 10% off orders of $20 or more
}
// in checkout():
double subtotal = cartTotal(store);
double discount = discountFor(subtotal);
double total = subtotal - discount;
// then pass 'discount' to printReceipt and print a "Discount: -$..." line2. Order history
Read orders.txt back with std::ifstream and print it. Add a menu option for it.
void showOrderHistory() {
std::ifstream file("orders.txt");
if (!file) {
std::cout << "No orders yet.\n";
return;
}
std::string line;
while (std::getline(file, line)) {
std::cout << line << "\n";
}
}3. Customer accounts that remember the balance
Save each customer’s balance in a small file named after them, and load it at the start. This is a learning example: real accounts need passwords and a database.
double loadBalance(const std::string& name) {
std::ifstream file(name + ".balance");
double balance;
if (file >> balance) return balance;
return 50.00; // new customer
}
void saveBalance(const std::string& name, double balance) {
std::ofstream file(name + ".balance");
file << balance;
}
// in main(): Store store = createStore(name, loadBalance(name));
// before exiting: saveBalance(store.customer, store.balance);4. Show products sorted by price
Sort a copy of the product list so the stock numbers in the real list are not changed. Add #include <algorithm>.
void displayProductsByPrice(const Store& store) {
std::vector<Product> sorted = store.products;
std::sort(sorted.begin(), sorted.end(),
[](const Product& a, const Product& b) { return a.price < b.price; });
for (const auto& p : sorted) {
std::cout << p.name << " - $" << p.price << "\n";
}
}Looking for more C++ projects with source code? Browse our C++ projects and the free practice sets.
Frequently Asked Questions About the C++ Online Grocery Store
Can you build an online grocery store in C++?
Yes, as a console program. C++ is not the usual choice for web back ends, but a console grocery store is a good way to practice structs, vectors, functions, input validation and file handling. A real website would use a web framework and a payment provider.
Why does the original grocery store code not compile?
Case 3 in the menu is missing a semicolon after break, and checkout() calls a getTotal() function that is never defined. It also crashes on a wrong product number because nothing validates the input. This version fixes all three.
Should prices be stored as double in C++?
For a learning project, double is fine if you print with two decimals. For real money, store prices in whole cents as integers to avoid rounding errors. The live demo above does this.
How should a C++ shop handle payment data?
Never store card numbers in your own files. Real shops send payments to a payment provider and store only a reference. This project uses a simple customer balance and stores only the order and the receipt.
How long does it take to learn C++?
Most beginners learn the basics (variables, functions, loops, structs and classes) in a few months of regular practice. Small projects like this one speed it up.
Keep Building with C++
You built a console online grocery store with structs, vectors, a validated menu, a cart, a balance-based checkout, receipts and an order file. This code is a starting point: change the products, add discounts and customer accounts, and put the project on GitHub with a README. Small projects like this are the fastest way to learn C++.
