[英]Why strlen() returns an unexpected value
我編寫了一個程序,該程序獲取一個字符串(密碼)並檢查其有效性,
字符串的條件是:
因此,我涵蓋了大多數情況,但是后來我對第三個條件感到困惑,我嘗試使用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;
}
我使用的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.
如果您希望密碼為6個字符,則緩沖區必須為7個字符:
\\0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.