C++ Online Compiler
Example: C++ Bill Statement Generator in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// C++ Bill Statement Generator #include <iostream> // For input/output operations #include <vector> // To store multiple item details #include <string> // For item names #include <iomanip> // For output formatting (e.g., std::setprecision) // Structure to hold item details struct Item { std::string name; int quantity; double unitPrice; double total; }; int main() { std::cout << "-------------------------------------------\n"; std::cout << " Simple Bill Statement Generator \n"; std::cout << "-------------------------------------------\n"; std::vector<Item> items; // A list to store all items char addMore = 'y'; double grandSubtotal = 0.0; const double TAX_RATE = 0.05; // 5% tax rate // Step 1: Input item details from the user while (addMore == 'y' || addMore == 'Y') { Item newItem; std::cout << "\nEnter Item Name: "; std::cin.ignore(); // Clear the buffer before reading string std::getline(std::cin, newItem.name); std::cout << "Enter Quantity: "; std::cin >> newItem.quantity; std::cout << "Enter Unit Price: $"; std::cin >> newItem.unitPrice; newItem.total = newItem.quantity * newItem.unitPrice; grandSubtotal += newItem.total; items.push_back(newItem); std::cout << "Add another item? (y/n): "; std::cin >> addMore; } // Step 2: Display the formatted bill statement std::cout << "\n\n--------------------------------------------------\n"; std::cout << " ABC Store - Bill \n"; std::cout << "--------------------------------------------------\n"; std::cout << std::left << std::setw(20) << "Item" << std::right << std::setw(8) << "Qty" << std::right << std::setw(12) << "Price" << std::right << std::setw(12) << "Total\n"; std::cout << "--------------------------------------------------\n"; // Use fixed and setprecision for currency formatting std::cout << std::fixed << std::setprecision(2); for (const auto& item : items) { std::cout << std::left << std::setw(20) << item.name << std::right << std::setw(8) << item.quantity << std::right << std::setw(12) << item.unitPrice << std::right << std::setw(12) << item.total << "\n"; } std::cout << "--------------------------------------------------\n"; double taxAmount = grandSubtotal * TAX_RATE; double finalTotal = grandSubtotal + taxAmount; std::cout << std::left << std::setw(40) << "Subtotal:" << std::right << "$" << std::setw(10) << grandSubtotal << "\n"; std::cout << std::left << std::setw(40) << "Tax (" + std::to_string(static_cast<int>(TAX_RATE * 100)) + "%):" << std::right << "$" << std::setw(10) << taxAmount << "\n"; std::cout << "--------------------------------------------------\n"; std::cout << std::left << std::setw(40) << "Total Amount Due:" << std::right << "$" << std::setw(10) << finalTotal << "\n"; std::cout << "--------------------------------------------------\n"; std::cout << "Thank you for your purchase!\n"; return 0; }
Output
Clear
ADVERTISEMENTS