C++ Online Compiler
Example: Basic Bank Account Transactions in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Basic Bank Account Transactions #include <iostream> // Required for input/output operations #include <limits> // Required for numeric_limits to clear input buffer using namespace std; int main() { double balance = 1000.00; // Initial account balance int choice; // To store user's menu choice double amount; // To store deposit or withdrawal amount cout << "Welcome to the Simple C++ Bank Account System!" << endl; // Loop to keep the program running until the user chooses to exit do { // Display the main menu cout << "\n--- Main Menu ---" << endl; cout << "1. Deposit Cash" << endl; cout << "2. Withdraw Cash" << endl; cout << "3. Check Balance" << endl; cout << "4. Exit" << endl; cout << "Enter your choice: "; cin >> choice; // Clear input buffer in case of invalid input (e.g., characters) // This prevents infinite loops if non-numeric input is given for 'choice' if (cin.fail()) { cin.clear(); // Clear the error flag cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Discard invalid input cout << "Invalid input. Please enter a number." << endl; choice = 0; // Reset choice to an invalid option to re-display menu continue; // Skip to the next iteration of the loop } // Process user's choice using a switch statement switch (choice) { case 1: // Deposit Cash cout << "\nEnter amount to deposit: $"; cin >> amount; if (cin.fail() || amount <= 0) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "Invalid deposit amount. Please enter a positive number." << endl; } else { balance += amount; // Add amount to balance cout << "Deposit successful! New balance: $" << balance << endl; } break; case 2: // Withdraw Cash cout << "\nEnter amount to withdraw: $"; cin >> amount; if (cin.fail() || amount <= 0) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "Invalid withdrawal amount. Please enter a positive number." << endl; } else if (amount > balance) { cout << "Insufficient funds! Current balance: $" << balance << endl; } else { balance -= amount; // Subtract amount from balance cout << "Withdrawal successful! New balance: $" << balance << endl; } break; case 3: // Check Balance cout << "\nYour current balance is: $" << balance << endl; break; case 4: // Exit Program cout << "\nThank you for using the Simple Bank Account System. Goodbye!" << endl; break; default: // Invalid choice cout << "Invalid choice. Please try again." << endl; break; } } while (choice != 4); // Continue loop until user chooses to exit (option 4) return 0; // Indicate successful program execution }
Output
Clear
ADVERTISEMENTS