[英]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.