我写了一个程序,它获取一个字符串(密码)并检查其有效性,
字符串的条件是:
所以我涵盖了大部分条件,但后来我对第三个条件感到困扰,我尝试使用strlen()
,但它返回了错误的值。
以下是代码:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <string.h>
#define MAX 6
#define TRUE 1
#define FALSE 0
int passCheck(char password[]);
/*
main will ask the user to enter a password and then it will send it to
passCheck, and check the return value, if the password is valid or not.
input: none
output: none
*/
int main()
{
char password[MAX] = { 0 };
printf("Enter a password: ");
fgets(password, MAX, stdin);
if(password[strlen(password)-1] = '\n') {password[strlen(password)-1] = 0;}
if (passCheck(password) == TRUE)
{
printf("Valid");
}
else
{
printf("Invalid");
}
return (0);
}
/*
passCheck will take the password and will see if it's meeting the conditions
, then passCheck will return true(valid) or false(invalid).
input: password string
output: flag
*/
int passCheck(char password[])
{
int i = 0;
int flag = FALSE; // true(1) or false(0)
int len = 0;
int checkInt = 0; // checks if password has a digit
int checkChar = 0;
int copy = 0;
for (i = 0; password[i]; i++)
{
if (strlen(password) == MAX)
{
len = TRUE;
}
if (isdigit(password[i]))/*checks if the input is a number(0-9) or
a char (A-Z, a-z)
*/
{
checkInt = TRUE;
}
if ((password[i] >= 'A' && password[i] <= 'Z') || (password[i] >= 'a' && password[i] <= 'z'))
{
checkChar = TRUE;
}
if (password[i] == password[i-1]) // checks if there is the same char/num in a row
{
copy = TRUE;
}
else
{
copy = FALSE;
}
}
printf("%d %d %d %d\n" , len,checkInt, checkChar,strlen(password));
if (copy)
{
flag = FALSE;
}
else if (len && checkInt && checkChar)
{
flag = TRUE;
}
return flag;
}
我使用的printf()
函数中的passCheck()
用于检查字符串是否符合条件,输出是否正常,但len
不起作用且strlen()
如果数字大于4,函数总是返回4.我在哪里出错?
答案 0 :(得分:4)
#define MAX 6
char password[MAX] = { 0 }; // The LONGEST your password can be is 5-characters + NULL Terminator (\0)
strlen(password); // will never return anything more than 5.
如果您希望密码为6个字符,则缓冲区必须为7个字符:
\0