我不知道如何进一步完成我即将创建的这个程序。这就是这个想法:
验证密码输入以检查密码是否至少有一个 大写字母,小写字母和数字。
此刻它的某些部分已被打破。例如,虚假的,真实的陈述。和主要功能中的“动态”char数组。我现在也不知道如何做到这一点。但它解释了我在寻找什么。
那么如何在不编写太多代码的情况下验证这一点呢?
这是我目前的代码:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int passval(char pw[])
{
int x;
for (x = 0; x < sizeof(pw); x++) {
if ( (isalnum(pw[x])) || (ispunct(pw[x])) ) {
return 0;
} else {
return 1;
}
}
return 0;
}
int main()
{
char password[20];
printf("Enter password: ");
scanf("%s", password);
if (passval(password) == TRUE) {
printf("Password is TRUE");
}
return 0;
}
答案 0 :(得分:1)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int
password_validate(const char *pass)
{
int upper = 0, lower = 0, digit = 0;
if (pass == NULL || strlen(pass) == 0)
return -1;
do
{
if (isupper(*pass))
upper = 1;
if (islower(*pass))
lower = 1;
if (isdigit(*pass))
digit = 1;
} while ((!lower || !upper || !digit) && *(++pass));
return (*pass != '\0' ? 0 : (upper == 0 ? -2 : (lower == 0 ? -3 : -4)));
}
请查看下面的代码示例链接,以确保了解一些极端情况(感谢Alex Pogue强调其他案例)以及此功能如何处理它们。
答案 1 :(得分:0)
示例实施:
#include <ctype.h>
int passval(const char pw[])
{
size_t x;
unsigned char c; /* making this unsigned is important:
char may be negative and passing it to isupper(), etc. may invoke undefined behavior */
int upperExists = 0, lowerExists = 0, numberExists = 0;
for (x = 0; pw[x] != '\0'; x++) {
/* fetch the character */
c = pw[x];
/* raise flags when the character is required kind */
upperExists = upperExists || isupper(c);
lowerExists = lowerExists || islower(c);
numberExists = numberExists || isdigit(c);
}
/* check if all of required flags are raised */
return upperExists && lowerExists && numberExists;
}
答案 2 :(得分:0)
我的解决方案是基于解析以\0
字符结尾的字符串,检查至少一个大写字母,小字符和数字,如OR门如何运行..
int passval(char * p)
{
int capital=0, small=0, digit=0;
while (*p && !(capital && small && digit))
capital = (*p>='A' && *p<='Z' ? 1 : capital),
small = (*p>='a' && *p<='z' ? 1 : small ),
digit = (*p>='0' && *p<='9' ? 1 : digit ),
p++ ;
return capital && small && digit;
}
答案 3 :(得分:0)
传递给函数的数组会衰减为指针,因此您无法在函数中执行sizeof(),而是传递字符串长度strlen()
我会做这样的事情
#include <ctype.h>
#include <stdbool.h>
bool validatePassword(const char* pw, const int len)
{
int x;
bool upperCase = false;
bool lowerCase = false;
bool number = false;
for (x = 0; x < len; x++)
{
if ( pw[x] == toupper(pw[x]) )
{
upperCase = true;
}
else if ( pw[x] == tolower(pw[x]) )
{
lowerCase = true;
}
else if ( isdigit(pw[x]) )
{
number = true;
}
}
return upperCase && lowerCase && number;
}
答案 4 :(得分:-1)