C++ Online Compiler
Example: Interactive Bill Generator in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Interactive Bill Generator #include <iostream> #include <vector> // For std::vector #include <string> // For std::string #include <iomanip> // For formatting struct BillItem { std::string name; int quantity; double price; double total; }; int main() { // Step 1: Initialize variables std::vector<BillItem> items; double subtotal = 0.0; char addMore = 'y'; int itemCounter = 1; // Step 2: Loop to get item details from user while (addMore == 'y' || addMore == 'Y') { BillItem currentItem; std::cout << "\nEnter details for Item " << itemCounter << ":\n"; std::cout << "Enter item name: "; std::cin.ignore(); // Consume the newline character left by previous cin std::getline(std::cin, currentItem.name); std::cout << "Enter quantity: "; std::cin >> currentItem.quantity; std::cout << "Enter price per item: $"; std::cin >> currentItem.price; currentItem.total = currentItem.quantity * currentItem.price; items.push_back(currentItem); subtotal += currentItem.total; std::cout << "Add another item? (y/n): "; std::cin >> addMore; itemCounter++; } // Step 3: Calculate Tax and Grand Total double taxRate = 0.08; // 8% tax double taxAmount = subtotal * taxRate; double grandTotal = subtotal + taxAmount; // Step 4: Print the bill std::cout << "\n----------------------------------------\n"; std::cout << std::setw(20) << "YOUR RECEIPT\n"; std::cout << "----------------------------------------\n"; std::cout << std::left << std::setw(15) << "Item" << std::right << std::setw(5) << "Qty" << std::right << std::setw(10) << "Price" << std::right << std::setw(10) << "Total\n"; std::cout << "----------------------------------------\n"; // Step 5: Print individual item details from vector for (const auto& item : items) { std::cout << std::left << std::setw(15) << item.name << std::right << std::setw(5) << item.quantity << std::right << std::setw(10) << std::fixed << std::setprecision(2) << item.price << std::right << std::setw(10) << std::fixed << std::setprecision(2) << item.total << "\n"; } std::cout << "----------------------------------------\n"; // Step 6: Print summary totals std::cout << std::left << std::setw(25) << "Subtotal:" << std::right << std::setw(15) << std::fixed << std::setprecision(2) << subtotal << "\n"; std::cout << std::left << std::setw(25) << "Tax (" << (taxRate * 100) << "%):" << std::right << std::setw(15) << std::fixed << std::setprecision(2) << taxAmount << "\n"; std::cout << "----------------------------------------\n"; std::cout << std::left << std::setw(25) << "Grand Total:" << std::right << std::setw(15) << std::fixed << std::setprecision(2) << grandTotal << "\n"; std::cout << "----------------------------------------\n"; std::cout << "Thank You!\n"; return 0; }
Output
Clear
ADVERTISEMENTS