Write a BankAccount whose balance can change only through deposit and withdraw (validated), which records every successful transaction, and exposes the history read-only. Process commands from the input.
#include <iostream>
#include <span>
#include <string>
#include <vector>
class BankAccount {
public:
struct Txn { char type; double amount; double balance_after; };
private:
double balance_ = 0;
std::vector<Txn> history_;
void record(char t, double a) { history_.push_back({t, a, balance_}); }
public:
bool deposit(double a) {
if (a <= 0) return false;
balance_ += a; record('D', a);
return true;
}
bool withdraw(double a) {
if (a <= 0 || a > balance_) return false;
balance_ -= a; record('W', a);
return true;
}
double balance() const { return balance_; }
std::span<const Txn> history() const { return history_; }
};
int main() {
BankAccount acc;
std::string cmd;
double amt;
while (std::cin >> cmd >> amt) {
bool ok = cmd == "deposit" ? acc.deposit(amt) : acc.withdraw(amt);
if (!ok) std::cout << "rejected: " << cmd << ' ' << amt << '\n';
}
for (const auto& t : acc.history()) std::cout << t.type << ' ' << t.amount << " -> " << t.balance_after << '\n';
std::cout << "balance " << acc.balance() << '\n';
return 0;
}
rejected: withdraw 9000 rejected: deposit -20 D 5000 -> 5000 W 1500 -> 3500 W 500 -> 3000 balance 3000
The balance and history are private and change together in one place, so they can never disagree. history() hands out a read-only span: callers can audit transactions but not forge them.