如何使用bool函数在C++中检查密码的强度

How to check the strength of a password in C++ using bool functions

本文关键字:密码 检查 C++ 何使用 bool 函数      更新时间:2024-04-28

为我的班级做一个练习。我的老师希望我们学习C字符串,而不是字符串类。我们必须使用bool函数和C字符串命令来确定密码是否足够强。我想我快要完了,但我肯定在哪里出了什么差错?这是我得到的:

#include <iostream>
#include <cstring>
#include <cctype>
bool checklength(char[]);
bool checkdigit(char[]);
bool checklower(char[]);
bool checkupper(char[]);
bool checkspecial(char[]);
int main()
{
char pwdstr[20];
std::cout << "Enter your passwordn";
std::cin >> pwdstr;
if (checklength(pwdstr) &&
checkdigit(pwdstr) &&
checklower(pwdstr) &&
checkupper(pwdstr) &&
checkspecial(pwdstr))
{
std::cout << "Your password is strong.n";
}
else
{
std::cout << "Your password is too weak!n";
}
}
bool checklength(char p[])
{
int i;
int len = strlen(p);
for (i = 0; i < len - 1;)
{
if (isalnum(p[i]))
{
i++;
}
}
if (i < 6)
{
std::cout << "Your password must be at least 6 characters 
long.n";
return false;
}
else
{
return true;
}
}
bool checkdigit(char p[])
{
int i;
int len = strlen(p);
for (i = 0; i < len - 1;)
{
if (isdigit(p[i]))
{
i++;
}
}
if (i < 1)
{
std::cout << "Your password must have at least 1 digit in 
it.n";
return false;
}
else
{
return true;
}
}
bool checklower(char p[])
{
int i;
int len = strlen(p);
for (i = 0; i < len - 1;)
{
if (islower(p[i]))
{
i++;
}
}
if (i < 1)
{
std::cout << "Your password must have at least 1 lower case 
letter in it.n";
return false;
}
else
{
return true;
}
}
bool checkupper(char p[])
{
int i;
int len = strlen(p);
for (i = 0; i < len - 1;)
{
if (isupper(p[i]))
{
i++;
}
}
if (i < 1)
{
std::cout << "Your password must have at least 1 upper case 
letter in it.n";
return false;
}
else
{
return true;
}
}
bool checkspecial(char p[])
{
int i;
int len = strlen(p);
for (i = 0; i < len - 1;)
{
if (ispunct(p[i]))
{
i++;
}
}
if (i < 1)
{
std::cout << "Your password must have at least 1 special 
character in it.n";
return false;
}
else
{
return true;
}
}

在返回false之前添加错误描述之前,我的当前输出是,由于某种原因,一切都是正确的。现在,我所尝试的一切都表明我的checklength函数失败了,密码太短了。

感谢所有

所有的循环都是错误的,您将测试字符的索引与通过测试的字符数混为一谈,为此需要单独的变量。另外,字符串的长度有一个错误,您有len - 1而不是len。所以这个

bool checklength(char p[])
{
int i;
int len = strlen(p);
for (i = 0; i < len - 1;)
{
if (isalnum(p[i]))
{
i++;
}
}
if (i < 6)
{
std::cout << "Your password must be at least 6 characters long.n";
return false;
}
else
{
return true;
}
}

应该是这个吗

bool checklength(char p[])
{
int count = 0;
int len = strlen(p);        
for (int i = 0; i < len; i++)
{
if (isalnum(p[i]))
count++;
}
if (count < 6)
{
std::cout << "Your password must be at least 6 characters long.n";
return false;
}
else
{
return true;
}
}

使用STL算法可以大大简化您的函数。例如checklength可以是:

bool checklength(char p[])
{
return std::count_if(p, p + strlen(p), [](unsigned char c) {
return std::isalnum(c); 
}) >= 6;
}

你可以为其他函数做类似的事情。