密碼驗證是系統安全的第一道防線。本文實作一個允許最多嘗試 3 次的密碼驗證程式,涵蓋字串比較、迴圈控制與安全性考量。
#include <stdio.h>
#include <string.h>
#define MAX_ATTEMPTS 3
#define PASSWORD "123456"
#define MAX_LEN 20
int main() {
char input[MAX_LEN];
int attempts = 0;
int success = 0;
printf("=== 登入系統 ===\n");
printf("預設密碼:%s(僅供測試)\n\n", PASSWORD);
while (attempts < MAX_ATTEMPTS) {
printf("請輸入密碼 (剩餘 %d 次機會): ", MAX_ATTEMPTS - attempts);
// 使用 fgets 讀取整行,避免 scanf 空格截斷問題
if (fgets(input, MAX_LEN, stdin) == NULL) {
printf("輸入讀取失敗\n");
continue;
}
// 移除換行符
input[strcspn(input, "\n")] = '\0';
if (strcmp(input, PASSWORD) == 0) {
printf("\n✅ 登入成功!歡迎回來。\n");
success = 1;
break;
} else {
attempts++;
if (attempts < MAX_ATTEMPTS) {
printf("❌ 密碼錯誤,請重新輸入。\n\n");
}
}
}
if (!success) {
printf("\n🔒 錯誤次數過多,帳號暫時鎖定。請稍後再試。\n");
}
return 0;
}
gets 已被 C11 標準移除(緩衝區溢位風險),scanf("%s") 遇空格截斷。fgets 可指定最大長度,安全可靠。strcspn(input, "\n") 找到換行符位置並置換為結束符。#define 管理嘗試次數、密碼、緩衝區大小,易於維護。termios 關閉回顯,Windows 用 _getch()// Linux/Unix 隱藏輸入
#include <termios.h>
#include <unistd.h>
void getPassword(char *buf, int maxLen) {
struct termios old, new;
tcgetattr(STDIN_FILENO, &old);
new = old;
new.c_lflag &= ~ECHO; // 關閉回顯
tcsetattr(STDIN_FILENO, TCSANOW, &new);
fgets(buf, maxLen, stdin);
tcsetattr(STDIN_FILENO, TCSANOW, &old); // 恢復
buf[strcspn(buf, "\n")] = '\0';
}