1

我正在尝试验证 C 中的密码,并且else每当代码运行时,我的其中一条语句就会自动触发。我运行测试以查看字符是否为符号,以及是否将 1 添加到int symbolusing 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");

}
4

3 回答 3

2

在您的代码中,更改

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

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

因为,C数组有0基础索引。否则,您可能会超出分配的内存,从而调用未定义的行为

注意:即使您没有超出内存(因为您有一个编译时分配的数组并且输入可能小于实际数组大小),您最终还是会比较 terminating nul,这可能是您不想要的。

然后,isdigit()检查不应该是独立 if的(根据您的逻辑),它应该是else ifwith isalpha()

也就是说,

 scanf("%s", &password);

应该

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

以避免任何可能的缓冲区溢出风险。

于 2015-05-21T16:48:08.097 回答
1

线

symbol++;

将在输入 alpha 时执行。

为防止这种情况,请在测试else前插入isdigit

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

正如其他人指出的那样,循环也不正确。它应该是

for (i = 0; i < len; i++) {
于 2015-05-21T16:53:09.787 回答
1

您的代码如下所示:

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

在这种情况下,-block 的执行else独立于cond1-block,如 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 {}
于 2015-05-21T16:53:13.967 回答