模擬登錄系統核心邏輯:預設密碼、三次嘗試、成功跳出、失敗鎖定,展示 scanf、strcmp、循環控制的綜合應用。
#include
#include
int main() {
char password[] = "123456"; // 預設密碼
char input[10];
int i;
for (i = 0; i < 3; i++) {
printf("please input the passwd:> ");
scanf("%s", input); // 注意:不需 &input
if (strcmp(password, input) == 0) {
printf("login success!\n");
break;
} else {
printf("passwd error, try again\n");
}
}
if (i == 3) {
printf("attempts exceeded, exiting...\n");
return 0;
}
// 登錄成功後續業務邏輯...
system("pause"); // Windows 專用,Linux 用 getchar()
return 0;
}
strcmp(s1, s2) == 0 表示相等,切勿用 == 比較數組名%s 遇空格停止,密碼含特殊字符需用 fgetsscanf("%s", input) 無長度限制,生產環境用 scanf("%9s", input) 或 fgetsbreak 跳出循環,i == 3 判斷是否耗盡機會*),需平台相關 API(getch/termios)此例雖簡單,但涵蓋:
是 C 語言入門項目的優秀實踐案例。