本專案模擬自動櫃員機核心流程:帳戶驗證、存取款、查詢餘額、修改密碼、資料持久化。採用模組化設計,核心資料結構為單向鏈表,檔案作為離線儲存。
// User.h
typedef struct User {
char UserAccount[17]; // 16 位卡號 + '\0'
char UserPassword[7]; // 6 位密碼 + '\0'
int Money; // 餘額(分為單位)
struct User *next; // 鏈表指標
} User;
User *head = NULL; // 鏈表頭
User *Current_user = NULL; // 當前登入用戶
| 模組 | 職責 | 關鍵函式 |
|---|---|---|
| UI | 選單顯示、畫面清理 | showMenu() |
| FileController | 帳戶檔案讀寫、初始化 | initdata(), writeIntoFile() |
| AccountController | 帳戶查找、密碼驗證、存取款邏輯 | checkAccount(), WithDraw(), Deposit() |
| Main | 主流程控制、使用者互動 | startATM(), OperationMenu() |
void initdata(FILE *fp, const char *path) {
if (fopen_s(&fp, path, "r+") == 0 && fgetc(fp) == EOF) {
// 檔案不存在或為空,寫入預設測試帳戶
initFile(fp, path);
}
rewind(fp);
User *user = (User*)malloc(sizeof(User));
Current_user = head = user;
while (fscanf_s(fp, "%16s %6s %d\n", user->UserAccount, 17,
user->UserPassword, 7,
&user->Money) != EOF) {
user->next = (User*)malloc(sizeof(User));
user = user->next;
}
fclose(fp);
}
注意:fscanf_s 需指定緩衝區大小,防止緩衝區溢位。
bool checkAccount(const char *account, User **outUser) {
User *p = head;
while (p) {
if (strcmp(p->UserAccount, account) == 0) {
*outUser = p;
Current_user = p;
return true;
}
p = p->next;
}
return false;
}
void InputPassword(const char *account, char *pwd) {
int i = 0;
system("cls");
printf("用戶名:"); showAccount(account);
printf("\n請輸入密碼:");
while ((pwd[i] = _getch()) != '\r') {
if (pwd[i] == 8 && i > 0) { i--; pwd[i] = '\0'; } // 退格
else if (pwd[i] >= '0' && pwd[i] <= '9' && i < 6) { i++; }
system("cls");
printf("用戶名:"); showAccount(account);
printf("\n請輸入密碼:");
for (int k = 0; k < i; ++k) putchar('*');
}
pwd[i] = '\0';
}
void WithDraw(int amount) {
if (amount > Current_user->Money) {
printf("餘額不足\n"); return;
}
Current_user->Money -= amount;
printf("取款成功,餘額:%d\n", Current_user->Money);
}
InputAccount → 輸入卡號checkAccount → 帳戶存在性檢查InputPassword + checkPasswordOperationMenu 循環:writeIntoFile 將鏈表資料覆寫回檔案gcc Main.c User.c UI.c FileController.c AccountController.c -o atm ./atm
依賴:Windows 平台需 conio.h(_getch)、system("cls");Linux 可替換為 termios 非標準輸入與 ANSI 轉義序列。
ATM/ ├── Main.c ├── User.h ├── UI.h ├── FileController.h ├── AccountController.h └── Makefile
各模組 .c 檔對應 .h 實作,主程式 Main.c 統籌流程。