簡體   English   中英

密碼驗證其他語句在不應該觸發時觸發

[英]Password Validation Else Statement Firing When It Shouldn't

我正在嘗試驗證C中的密碼,並且每當代碼運行時,我的else語句之一就會自動觸發。 我運行測試以查看字符是否為符號,以及是否使用symbol++;將其添加到int symbol symbol++;否則為1 symbol++; ,但是問題是無論我測試的字符是否是符號,該代碼都在執行。

我認為這個問題與if, else語句的結構有關,並且我嘗試了幾種組合,但是某些錯誤使該程序退出了我所使用的else if但那沒有幫助。 這似乎應該很明顯,但是我似乎無法弄清楚出了什么問題。

char password[30];
int lower, upper, number, symbol, i;
lower = upper = number = symbol = 0;

printf("Enter your password: ");
scanf("%s", &password);

int len = strlen(password);

for (i = 0; i <= len; i++) {

    if (isalpha(password[i])){

        if (isupper(password[i])){
            upper++;
        }

        else{
            lower++;
        }
    }

    if (isdigit(password[i])){
        number++;
    }

    else{
        symbol++;
    }
}

if (upper >= 1 && lower >= 1 && number >= 1 && symbol >= 1 && len >=6){

    printf("Your password is good!");

}

if (upper < 1){

    printf("You need an uppercase letter \n");

}

if (lower < 1){

    printf("You need a lowercase letter \n");

}

if (number < 1){

    printf("You need a number \n");

}

if (symbol < 1){

    printf("You need a symbol \n");

}

if (len < 6){

    printf("Your password must be at least 6 characters \n");

}

在您的代碼中,更改

for (i = 0; i <= len; i++) 

for (i = 0; i < len; i++) 

as, C數組具有從0的索引。 否則,您可能會超出分配的內存,從而又調用了undefined behavior

注意:即使不溢出內存(因為您有分配編譯時間的數組並且輸入的數據可能小於實際的數組大小),您最終還是會比較終止nul ,這可能是您不想要的。

然后, isdigit()檢查不應該獨立if (按照您的邏輯)), else if使用isalpha()應該是else if

那就是

 scanf("%s", &password);

應該

 scanf("%29s", &password);

以避免任何可能的緩沖區溢出風險。

symbol++;

輸入字母時將執行。

為防止這種情況,請在等isdigit測試之前插入else

else if (isdigit(password[i])) {

另外,正如其他人指出的那樣,循環是不正確的。 它應該是

for (i = 0; i < len; i++) {

您的代碼如下所示:

if (cond1){}
if (cond2){}
else {}

在這種情況下, else cond1執行獨立於cond1 ,如C11草案標准第6.8.4.1節所述:$ 3: An else is associated with the lexically nearest preceding if that is allowed by the syntax.

您可以將代碼的結構更改為:

if (cond1){}
else if (cond2){}
else {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM