首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C 語言終端機密碼驗證系統:三次嘗試限制與字串比對

     編輯:關於C語言

C 語言終端機密碼驗證系統:三次嘗試限制與字串比對

完整程式碼

#include <stdio.h>
#include <string.h>

int main() {
    const char *password = "123456";
    char input[20];
    int attempts = 3;

    while (attempts > 0) {
        printf("輸入密碼 (剩餘 %d 次): ", attempts);
        if (scanf("%19s", input) != 1) { puts("輸入錯誤"); continue; }

        if (strcmp(input, password) == 0) {
            puts("登入成功!");
            break;
        } else {
            --attempts;
            if (attempts > 0) puts("密碼錯誤,請重試");
            else puts("嘗試次數用盡,帳號鎖定");
        }
    }
    return 0;
}

關鍵點

  1. 字串比對用 strcmp:== 比較指標位址,非內容。
  2. 緩衝區大小限制:%19s 防止溢位 (留 1 位給 \0)。
  3. 計數器邏輯:成功 break,失敗遞減,歸零鎖定。
  4. 安全性提醒:真實系統應用雜湊 (bcrypt/Argon2) 存儲密碼,不可明文。

改進方向

  • 隱藏輸入 (關閉回顯,平台相關)。
  • 鎖定後延遲或通知管理員。
  • 支援多用戶 (結構體陣列/檔案/資料庫)。

此範例展示基本 I/O、字串操作、流程控制整合,適合入門練習。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved