需求分析
- 預設密碼 "123456"。
- 最多嘗試 3 次。
- 成功:顯示歡迎並結束。
- 失敗 3 次:提示鎖定,延遲 3 秒後退出(模擬系統關機)。
參考實作
#include <stdio.h>
#include <string.h>
#include <windows.h> // Sleep()
int main() {
const char *password = "123456";
char input[20];
int i;
for (i = 0; i < 3; i++) {
printf("請輸入密碼: ");
if (scanf("%19s", input) != 1) { // 限制寬度防溢位
puts("輸入錯誤!");
while (getchar() != '\n');
i--; // 不計入失敗次數
continue;
}
if (strcmp(password, input) == 0) {
puts("恭喜你登錄成功!");
break;
} else {
puts("密碼錯誤!");
}
}
if (i == 3) {
puts("三次密碼輸入錯誤,系統將在3秒後自動關閉!");
Sleep(3000); // Windows API,毫秒
// Linux 跨平台寫法:#include sleep(3);
}
return 0;
}
安全性與健壯性增強
- 輸入長度限制:
%19s 留 1 字元給 \0,防止緩衝區溢位。
- 掩碼輸入:真實系統應用
getch() (Windows) 或 termios (Linux) 隱藏輸入字元,避免肩窺。
- 密碼不硬編碼:應存儲雜湊值(如 bcrypt),而非明文。
- 跨平台延遲:
#ifdef _WIN32
#include
#define SLEEP(ms) Sleep(ms)
#else
#include
#define SLEEP(ms) usleep((ms)*1000)
#endif
- 失敗計數持久化:真實場景需寫入檔案/登錄,防止重啟繞過。
執行結果
# 失敗案例
請輸入密碼: 123567
密碼錯誤!
請輸入密碼: 65848
密碼錯誤!
請輸入密碼: 135268
密碼錯誤!
三次密碼輸入錯誤,系統將在3秒後自動關閉!
# 成功案例
請輸入密碼: 123456
恭喜你登錄成功!