How to check whether a given password is strong, medium, or weak in C++

1 Answer

0 votes
#include <iostream>
#include <string>
 
// You can set your own rules
 
std::string checkPasswordStrength(const std::string password) {
    int length = password.length();

    bool hasLower = false, hasUpper = false;
    bool hasDigit = false, specialChar = false;
     
    std::string lowuppdig = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
 
    for (int i = 0; i < length; i++) {
        if (islower(password[i]))
            hasLower = true;
        if (isupper(password[i]))
            hasUpper = true;
        if (isdigit(password[i]))
            hasDigit = true;
 
        size_t special = password.find_first_not_of(lowuppdig);
        if (special != std::string::npos) {
            specialChar = true;
        }
    }
 
    if (hasLower && hasUpper && hasDigit && specialChar && length >= 10)
        return "Strong";
    else if ((hasLower || hasUpper) && specialChar && length >= 8)
        return "Medium";
         
    return "Weak";
}
 
int main(){
    const std::string password = "aq1o@p9$XM";
    
    std::cout << checkPasswordStrength(password) << "\n";
    
    std::cout << checkPasswordStrength("asW!W)(o") << "\n";
    std::cout << checkPasswordStrength("WSDFK!#Q") << "\n";
    std::cout << checkPasswordStrength("n*djskq*") << "\n";
        
    std::cout << checkPasswordStrength("WE3q#$") << "\n";
}
 
 
    
/*
run:
    
Strong
Medium
Medium
Medium
Weak
 
*/

 

 



answered Oct 21, 2024 by avibootz
edited Oct 22, 2024 by avibootz
...