Many programs work like this: show a menu, read a command, do it, repeat until the user quits. Here is a tiny bank:
#include <stdio.h>
typedef struct {
int balance;
int transactions;
} Account;
void deposit(Account *acc, int amount) {
acc->balance += amount;
acc->transactions++;
printf("Deposited %d. Balance: %d\n", amount, acc->balance);
}
void withdraw(Account *acc, int amount) {
if (amount > acc->balance) {
printf("Not enough money! Balance: %d\n", acc->balance);
return;
}
acc->balance -= amount;
acc->transactions++;
printf("Withdrew %d. Balance: %d\n", amount, acc->balance);
}
int main() {
Account acc;
acc.balance = 0;
acc.transactions = 0;
char command;
int amount;
scanf(" %c", &command);
while (command != 'q') {
if (command == 'd') {
scanf("%d", &amount);
deposit(&acc, amount);
} else if (command == 'w') {
scanf("%d", &amount);
withdraw(&acc, amount);
} else if (command == 'b') {
printf("Balance: %d\n", acc.balance);
} else {
printf("Unknown command %c\n", command);
}
scanf(" %c", &command);
}
printf("Goodbye! %d transactions.\n", acc.transactions);
return 0;
}Input (what the user types)
d 100 w 30 w 500 b x q
Output
Deposited 100. Balance: 100 Withdrew 30. Balance: 70 Not enough money! Balance: 70 Balance: 70 Unknown command x Goodbye! 2 transactions.
What to notice
- The loop keeps going until the user types
q. " %c"(with a space) skips theEnterkeys between commands.- The functions get a pointer to the account, so they change the real one.
withdrawuses an earlyreturnto refuse a withdrawal that is too big.
Tip: Ideas to extend it: add an interest command, or keep several accounts in an array.