Build a Simple Bank Account Manager in C++
Create a basic console application in C++ to simulate a simple bank account manager that allows a user to deposit, withdraw, and check their balance.
Challenge prompt
Write a C++ program that defines a class called BankAccount. This class should have private attributes for the account balance and public methods to deposit money, withdraw money (if sufficient funds exist), and check the current balance. Your program should create an instance of BankAccount, allow the user to perform multiple operations via simple menu choices, and print the updated balance after each operation. Implement basic input validation to ensure no negative deposits or withdrawals more than the current balance occur.
Guidance
- • Define a BankAccount class with a private balance attribute.
- • Implement public methods: deposit(double amount), withdraw(double amount), and getBalance().
- • Create a loop in main() to display a menu and process user input for multiple operations.
- • Validate inputs to prevent invalid deposit or withdrawal amounts.
Hints
- • Initialize the balance to zero in the BankAccount constructor.
- • Use if statements to check that deposit is positive and withdrawal does not exceed balance.
- • Use a while loop in main() to keep prompting the user until they choose to exit.
Starter code
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance;
public:
BankAccount() {
balance = 0.0;
}
void deposit(double amount) {
// Implement deposit logic here
}
bool withdraw(double amount) {
// Implement withdraw logic here
return false;
}
double getBalance() {
return balance;
}
};
int main() {
BankAccount myAccount;
int choice;
double amount;
do {
cout << "\nBank Account Menu:\n";
cout << "1. Deposit\n";
cout << "2. Withdraw\n";
cout << "3. Check Balance\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch(choice) {
case 1:
cout << "Enter amount to deposit: ";
cin >> amount;
// Call deposit method
break;
case 2:
cout << "Enter amount to withdraw: ";
cin >> amount;
// Call withdraw method
break;
case 3:
cout << "Current balance: $" << myAccount.getBalance() << endl;
break;
case 4:
cout << "Exiting program.\n";
break;
default:
cout << "Invalid choice. Please try again.\n";
}
} while (choice != 4);
return 0;
}
Expected output
Bank Account Menu: 1. Deposit 2. Withdraw 3. Check Balance 4. Exit Enter your choice: 1 Enter amount to deposit: 100 Deposit successful. Current balance: $100 Bank Account Menu: 1. Deposit 2. Withdraw 3. Check Balance 4. Exit Enter your choice: 2 Enter amount to withdraw: 50 Withdrawal successful. Current balance: $50 Bank Account Menu: 1. Deposit 2. Withdraw 3. Check Balance 4. Exit Enter your choice: 3 Current balance: $50 Bank Account Menu: 1. Deposit 2. Withdraw 3. Check Balance 4. Exit Enter your choice: 4 Exiting program.
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.