我正在尝试用 c 编写一个程序,检查输入的输入是否包含大写字母和数字。如果是这样,它输出输入是好的,如果输入仅包含大写字母或仅包含数字或没有,则输出它是坏的。但是当我运行代码并输入仅包含数字的输入时,它仍然输出输入良好。这是我的代码,有人能指出是什么原因造成的吗?
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#include<math.h>
int main()
{
int uppercase, digit = 0;
int i;
char pass [100];
printf("Please input a password\n");
scanf(" %s", pass);
for(i=0;i<=100;i++)
{
if(isupper(pass[i])){uppercase = 1;}
if(isdigit(pass[i])){digit = 1;}
}
if(uppercase==1 && digit==1){printf("Your password is good!");
}else{printf("Your password sucks");}
return 0;
}
最佳答案
您正在将char pass [100]
分配为自动局部变量。这意味着它将被放置在函数的堆栈帧中。以这种方式分配的变量不会初始化为任何特定值,其内容未定义。
如果您输入密码“test”,您将获得
pass[0] == 't'
pass[1] == 'e'
pass[2] == 's'
pass[3] == 't'
pass[4] == '\0'
pass[5] == ????
pass[5]
可以是任何值,包括大写字母或数字。您的“for”循环正在读取这些未初始化的值并给出错误的结果。
要解决此问题,请让 for 循环在遇到“\0”或“null”字符时停止。
for(i=0;pass[i]!='\0';i++)
如果密码太长,此代码将暴露安全漏洞。
关于c - 用c编写的程序检查数字和大写字母不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31593150/