c++ - 如何检查字符串是否包含所有这些 : digits, 字母和特殊字符?

标签 c++

我正在尝试构建一个简单的密码验证器:

程序打印

  • 如果密码少于 8 个字符且全部为数字,则“非常弱”。

  • 如果密码少于 8 个字符且全部为字母,则为“弱”。

  • 如果密码包含 8 个或更多字符且包含数字和字母,则为“强”。

  • 如果密码包含 8 个或更多字符并包含数字、字母和特殊字符,则为“非常强”。

正如您所看到的,我知道如何检查字符串是否具有三种类型的字符之一。 如何检查一个字符串是否包含两个或全部三个?

#include <iostream>
#include <ctype.h>
#include <cstring>

int main()
{
    std::cout << "Enter your new password: ";
    std:: string password{};
    std::cin >> password;

    bool veryweak;
    bool weak;
    bool strong;
    bool verystrong;

    if (password.length() < 8)
    {
        for (int i = 0; i < password.length(); i++)
            {
                if (isdigit(password[i]))
                {
                    veryweak = true;
                }

                else if (isalpha(password[i]))
                {
                    weak = true;
                }
            }
    }

    else if (password.length() >= 8)
    {
        for (int i = 0; i < password.length(); i++)
        {
            //if (password has digits and alphabets)
                //strong = true;

            //if (password has digits and alphabet and special characters)
                //verystrong = true;
        }
    }

    else
    {
        std::cout << "Password is invalid.";
    }
    //---------------------------------------------------------------------------------------------------------------------
    if (veryweak)
    {
        std::cout << "Your password is very weak.";
    }

    else if (weak)
    {
        std::cout << "Your password is weak.";
    }

    else if(strong)
    {
        std::cout << "Your password is strong.";
    }

    else if (verystrong)
    {
        std::cout << "Your password is very strong.";
    }

    return 0;
}

最佳答案

我会介绍 bool 值:

  • isShortPassword
  • 包含数字
  • 包含字母
  • 包含特殊字符

比你能写的

std::string passwortStrengt () {
    if (isShortPassword && !containsAlphabet && !containsSpecialCharacters) {
        return "weak";
    //forumlate all cases as you did in prosa up above
    } else if (...) {
    } else if (...) {
    } 
    return "weak"; // just in case you missed a case above
}

关于c++ - 如何检查字符串是否包含所有这些 : digits, 字母和特殊字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58814353/

相关文章:

c++ - 我可以强制 C++ 类使用最小空间量进行编译吗?

java - 使用 gcc 创建共享库

c++ - 将多个元素添加到 map<pair> c++

c++ - Qt 在自定义渲染控件上绘制小 'x' 图标

c++ - 如何在收到 2 个数据包后唤醒线程

c++ - iOS OpenCV cvtColor 未知数组类型错误

c++ - Qt 错误 : Searching for a function that does not exist

c++ - 使用 C++ 编写带有字节顺序标记 (BOM) 的 csv 文件?

c++ - 在可执行文件的资源中,如何找到默认图标?

c++ - 删除动态分配的数组与单个指针