How to validate a password (must contain uppercase, lowercase, digit, and special character) in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <cctype>

// One function that checks if the password is valid
bool isValidPassword(const std::string& pass) {
    bool upper = false, lower = false, digit = false, special = false;

    for (char c : pass) {
        if (isupper(c)) upper = true;
        else if (islower(c)) lower = true;
        else if (isdigit(c)) digit = true;
        else if (std::string("!@#$%^&*").find(c) != std::string::npos) special = true;
    }

    return upper && lower && digit && special;
}

int main() {
    std::string password1 = "aT5#op09!";
    if (isValidPassword(password1))
        std::cout << "Valid password\n";
    else
        std::cout << "Invalid password\n";
        
    std::string password2 = "aT#opQ!";
    if (isValidPassword(password2))
        std::cout << "Valid password\n";
    else
        std::cout << "Invalid password\n";
}


/*
run:

Valid password
Invalid password

*/

 



answered Apr 25 by avibootz

Related questions

...