输入用户的密码,然后检查密码是否包含字符,字母和数字 [英] Input a password from the user and check if it has a char, alphabet and digit

查看:265
本文介绍了输入用户的密码,然后检查密码是否包含字符,字母和数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的疑问是,如果我输入填充数组的密码,该程序就可以正常运行.但是,如果我输入诸如"apple25"之类的密码,我认为它会将数组中的空格算作字符,甚至声明"apple25"为有效密码.

My doubt is that, the program works fine if I enter a password that fills the array. However if I enter a password such as "apple25", I think it counts the blank spaces in the array as characters and even declares "apple25" as a valid password.

如何防止这种情况发生?它将字符串终止符也算作char吗?因为甚至"AAPPLLEE2"都是有效的密码.

How do I prevent this from happening? Does it count the string terminator also as a char? Because even "AAPPLLEE2" comes as a valid password.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define TRUE 1
#define FALSE 0


int main()
{
    char arr[10];
    printf("Enter a password. \n");
    scanf("%s",arr );
   // printf(arr);
    char ch;
    int i;
    int alp=0, dig=0, c=0;


    for (i=0; i<10; i++)
    {
       ch=arr[i];

       if(isalpha(ch))
       {
           alp++;
          // printf(" alpha is %d \n",alp);
       }
       else if(isdigit(ch))
       {
           dig++;
          // printf("digit is %d \n",dig);
       }
       else
       {
           c++;
         //  printf("charectores are %d \n",c);
       }

    }
    if(alp>=1&&dig>=1&&c>=1)
        {
            printf("Valid Password");
        }
    else{
            printf("Invalid Password");
        }
        return 0;
}

推荐答案

  • 要点1.始终初始化自动局部变量.避免意外访问未初始化的值.

    • Point 1. Always initialize your automatic local variables. Saves you from accidentally accessing un-initialized value.

      char arr[10] = {0};
      

    • 要点2.始终限制输入长度.通过超出预期的输入来使分配的内存溢出,从而使您免于陷入未定义行为. /p>

    • Point 2. Always limit your input length. Saves you from running into undefined behavior by overrunning the allocated memory by longer-than-expected input.

      scanf("%9s",arr );
      

    • 第3点.使用 strlen() 仅遍历输入的有效部分.

    • Point 3. Use strlen() to loop over only the valid part of input.

      这篇关于输入用户的密码,然后检查密码是否包含字符,字母和数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆