#include#include int main() { const char *password = "123456"; char input[20]; int attempts = 0; for (attempts = 0; attempts < 3; attempts++) { printf("Enter password: "); scanf("%19s", input); // 限制長度防溢位 if (strcmp(password, input) == 0) { puts("Login success!"); break; } else { puts("Wrong password!"); } } if (attempts == 3) puts("3 failures. System locked."); return 0; }
| 細節 | 說明 |
|---|---|
| `%19s` | 限制讀取長度,留 1 位給 `\0`,防止緩衝區溢位 |
| `strcmp` | 字串比較,相等回傳 0 |
| `for` 迴圈控制次數 | 比 `while` 更清晰表達「最多 3 次」 |
| 密碼隱藏輸入 | 真實系統應用 `getch()` 或終端機關閉回顯,此處為教學簡化 |
三次密碼嘗試是基礎安全機制。核心在於:`for` 迴圈計數、`strcmp` 比較、`scanf` 寬度限制。實務開發務必加入雜湊、限流、日誌審計等防護層。