[英]Why strlen() returns an unexpected value
I wrote a program that gets a string (password) and checks its validity, 我编写了一个程序,该程序获取一个字符串(密码)并检查其有效性,
the conditions for the string are: 字符串的条件是:
So I covered the most of the conditions, but then I got troubled with the third condition, I tried using strlen()
but it returned a wrong value. 因此,我涵盖了大多数情况,但是后来我对第三个条件感到困惑,我尝试使用
strlen()
但是返回了错误的值。
Here is the code: 这是代码:
#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;
}
The printf()
in the passCheck()
function I used is for checking if the string meets the conditions, the output is working well, however len
is not working and the strlen()
function always returns 4 if the number is great than 4. Where did I go wrong? 我使用的
passCheck()
函数中的printf()
用于检查字符串是否满足条件,输出是否正常运行,但是len
不起作用,并且如果数字大于4,则strlen()
函数始终返回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.
If you want your password to be 6 characters, the buffer has to be 7-characters: 如果您希望密码为6个字符,则缓冲区必须为7个字符:
\\0
\\0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.