gpt4 book ai didi

c - 密码验证 Else 语句在不应该触发时触发

转载 作者:太空宇宙 更新时间:2023-11-04 01:26:16 25 4
gpt4 key购买 nike

我正在尝试在 C 中验证密码,并且我的 else 语句之一会在代码运行时自动触发。我运行一个测试来查看一个字符是否是一个符号,如果它是使用 symbol++;int symbol 加 1,但问题是这段代码无论怎样都在执行我正在测试的字符是否是一个符号。

我认为这个问题与我的 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++) 

因为,C 数组具有基于 0 的索引。否则,您可能会超出分配的内存,这又会调用 undefined behaviour .

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

然后,isdigit() 检查不应该是一个独立 if(按照您的逻辑),它应该是一个 else ifisalpha()

也就是说,

 scanf("%s", &password);

应该是

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

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

关于c - 密码验证 Else 语句在不应该触发时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30379742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com