我的程式正在繼續回圈而不是跳出回圈。
輸入錯誤的密碼后,程式會要求用戶重新輸入密碼(應該如此)。雖然,如果用戶正確輸入密碼,在之前輸入錯誤的密碼后,程式會在應該跳出回圈時繼續要求他們重新輸入密碼。
如果用戶在第一次嘗試時輸入正確的密碼,我的程式將執行,盡管它使用戶單擊兩次而不是一次回車鍵。
我無法弄清楚出了什么問題。任何幫助表示贊賞。
#define ENTER 13
#define TAB 9
#define BKSP 8
#define SPACE 32
#define PASSWORD "HelloWorld"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char password[100];
char ch;
int i = 0;
do {
printf("\n\n\t\t\t\t\tPlease enter your password: ");
while (1) {
ch = getch();
if (ch == ENTER) {
password[i] = '\0';
break;
}
else if (ch == BKSP) {
if (i > 0) {
i--;
printf("\b \b");
}
}
else if (ch == TAB || ch == SPACE) {
continue;
}
else {
password[i] = ch;
i ;
printf("*");
}
}
} while((strcmp(password, PASSWORD) != 0));
return 0;
}
uj5u.com熱心網友回復:
最小的解決方法是將 移動int i = 0;到do {}回圈中,以便重置每個錯誤的密碼:
do {
int i = 0;
printf("\n\n\t\t\t\t\tPlease enter your password: ");
當您依賴固定大小的緩沖區時,您還應該檢查i < 100. 例如:
#define PASSWORD_MAX_LEN 99
char password[PASSWORD_MAX_LEN 1];
...
while(i < PASSWORD__MAX_LEN) {
ch = getch();
if (ch == ENTER) {
break;
}
...
}
password[i] = '\0';
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/339613.html
上一篇:為什么我需要為Java中的亂數猜測器的int分配-1
下一篇:為什么我的回圈在滿足條件時停止
