1

我制作了一个密码检查程序,它检查以下标准:-

  • 至少应该有

    • 1个大写
    • 1个小写
    • 1 个特殊字符
    • 1 个号码
  • 应少于 100 个字符

就是这样。我没有给出任何下限。而且无论我给出什么输入(正确或不正确),程序都会给我与截图中所附相同或相似的输出。

例如:- Pratik10, pratik10, pratikten, pr@tiK10, 我得到相同的输出"Password is fine and valid"

为什么我的程序没有正确检查定义的条件?它甚至没有正确打印密码的计数器。

以下是我的代码:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <string.h>

int main()
{
    char x[100];
    int i;
    int uc=0;
    int lc=0;
    int num=0;
    int misc=0;

    printf("enter your password\n");
    scanf("%s",x);

    for(i=0;i<100;i++) {
        if (isalpha(x[i])) {
            if (isupper(x[i])) {
                uc++;
            }
            if (islower(x[i])) {
                lc++;
            }
        }
        if (isdigit(x[i])) {
            num++;
        }
        else {  
            misc++;
        }
    }

    printf("checking your password\n");
    printf("%d uc\n",uc);
    printf("%d lc\n",lc);
    printf("%d num\n",num);
    printf("%d misc\n",misc);

    if ((uc > 0) && (lc > 0) && (num > 0) && (misc > 0)) {
        printf("password is fine and valid\n");
    }
    else {
        if(lc<=0) {
            printf("lowercase character(s) missing cannot proceed without inclusion\n");
        }
        if(uc<=0) {
            printf("uppercase character(s) missing cannot proceed without inclusion\n");
        }
        if(num<=0) {
            printf("number(s) missing cannot proceed without inclusion\n");
        }
        if(misc<=0) {
            printf("special character(s) missing cannot proceed without inclusion\n");
        }
        printf("please include all the missing parameters in combination to validate the password and try again\n\n");
    }

    return 0;
}

如何纠正这个?

输出:

在此处输入图像描述

4

3 回答 3

6

问题是您正在检查整个数组,该数组大多未初始化并且随机包含各种字符。

'\0'因此,遇到字符时必须退出循环。

于 2015-06-27T09:10:02.330 回答
4

您应该只检查作为用户输入提供的以空字符结尾的字符串。

换句话说,您应该迭代x直到遇到空字符。


改变这个:

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

对此:

for (i = 0; x[i] != 0; i++)

第二个问题是你没有if/else正确使用。

结果,每个不是数字的字符都被计为杂项。


改变这个:

if (isdigit(x[i]))

对此:

else if (isdigit(x[i]))
于 2015-06-27T09:09:18.953 回答
4

其他答案提到了主要问题。还有一个问题:else之前缺少一个if (isdigit(x[i])) {num++;}

for(i=0; x[i]!=0; i++)
{
   if (isalpha(x[i]))
   {
      if (isupper(x[i])) {uc++;}
      if (islower(x[i])) {lc++;}
   }
   else if (isdigit(x[i])) {num++;} // a missing else
   else {misc++;}
}
于 2015-06-27T09:16:24.247 回答