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

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

问题描述

我的疑问是,如果我输入填充数组的密码,程序可以正常工作.但是,如果我输入诸如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. 
");
    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 
",alp);
       }
       else if(isdigit(ch))
       {
           dig++;
          // printf("digit is %d 
",dig);
       }
       else
       {
           c++;
         //  printf("charectores are %d 
",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 点.始终限制输入长度.通过超出预期的输入超出分配的内存,使您免于遇到未定义的行为.

      scanf("%9s",arr );
      

    • 第 3 点.使用 strlen() 只循环输入的有效部分.

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

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