C 故障,不明原因
我必须检查密码。当密码包含大写、小写、数字和至少8个字符时,密码为强密码。我写了这个C程序,但它总是显示“弱密码”。我不知道原因C 故障,不明原因,c,C,我必须检查密码。当密码包含大写、小写、数字和至少8个字符时,密码为强密码。我写了这个C程序,但它总是显示“弱密码”。我不知道原因 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define N 50 int strenght(char word[],int length) { int sup = 0; int low =
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define N 50
int strenght(char word[],int length)
{
int sup = 0;
int low = 0;
int dig = 0;
for(int i = 0; i < length; i++)
{
if(isupper(word[i]) == 1)
sup++;
else if(islower(word[i]) == 1)
low++;
else if(isdigit(word[i]) == 1)
dig++;
}
if(sup > 0 && low > 0 && dig > 0 && length >= 8)
return 1;
else
return 0;
}
int main()
{
printf("Type the password until '*'\n");
char word[N];
while(1)
{
printf("Password: ");
fgets(word, N, stdin);
int length = strlen(word) - 1;
if(word[0] == '*')
break;
else
{
if(strenght(word, length) == 1)
printf("Strong password\n");
if(strenght(word, length) == 0)
printf("Weak password\n");
}
}
return 0;
}
#包括
#包括
#包括
#包括
#定义N 50
int-strength(字符单词[],int-length)
{
int-sup=0;
int低=0;
int-dig=0;
for(int i=0;i0&&low>0&&dig>0&&length>=8)
返回1;
其他的
返回0;
}
int main()
{
printf(“键入密码直到“*”\n”);
字符字[N];
而(1)
{
printf(“密码:”);
fgets(字,N,标准输入);
int-length=strlen(字)-1;
如果(字[0]=='*')
打破
其他的
{
如果(强度(字、长度)==1)
printf(“强密码”);
如果(强度(字、长度)==0)
printf(“弱密码”);
}
}
返回0;
}
问题在于,您正在比较isupper
、islower
和isdigit
调用1
的结果。别这样!如果条件不满足,这些函数中的每一个都将返回零,如果条件满足,则返回任何非零值。(见附件)
因此,代替:
if(isupper(字[i])==1)
sup++;
只要这样做:
if(isupper(字[i]))
sup++;
或者,如果要保持比较的明确性质,请使用:
if(isupper(字[i])!=0)
sup++;
(对于其他测试也是如此。)if(isupper(word[i])==word[i])sup++其余部分也是一样。@DavidRanieri-他正在避免使用
fgets()中的'\n'
,但他应该检查strlen(word)>0以避免出现负索引。@DavidC.Rankin yesh;)isupper('e')
(或ASCII-7范围之外的其他字符)可能会失败。最好使用强制转换更安全:isupper((unsigned char)“é”)
@pmg Good point!我不确定,但是像重音字母这样的情况可以通过区域设置处理吗?@pmg为什么这样更安全?isupper()
函数将一个int
作为其参数,如果它是标准定义的大写字母之一(即拉丁字母表中的26个大写字母),则(在C语言环境中)返回true。因此,对于其他任何内容,它只会返回false.:“如果[参数不能表示为无符号字符],则行为未定义”@pmg Wow,好吧。。。我明白了。我讨厌标准没有在实际章节中至少提到未定义行为(或允许值的范围)的小注释