How to generate a random password in C++

3 Answers

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

std::string generatePassword(int password_length) {
    const std::string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!$()";
    std::string password;
    int charset_len = charset.length();
    
    std::srand(std::time(0)); // Seed for random number generation

    for (int i = 0; i < password_length; i++) {
        password += charset.at(std::rand() % charset_len);
    }
    
    return password;
}

int main() {
    std::cout << generatePassword(10) << std::endl;
}

 
 
/*
run:
 
Aj)KiGrn(F

*/

 



answered Dec 22, 2024 by avibootz
0 votes
#include <iostream>
#include <ctime>

std::string generatePassword(int password_length) {
    std::srand(std::time(nullptr));
    std::string password(password_length, '*'); 
    
    for (int i = 0; i < password_length; i++) {
        password[i] = std::rand() % (126 - 33 + 1) + 33;
    }
    
    return password;
}

int main() {
    std::string password = generatePassword(10);

    std::cout << password << std::endl;
}


 
 
/*
run:
 
X6GM;s7kAu

*/

 



answered Dec 22, 2024 by avibootz
0 votes
#include <iostream>
#include <ctime>

std::string generatePassword(int password_length) {
    std::srand(std::time(nullptr));
    std::string password = "";
    
    for (int i = 0; i < password_length; i++) {
        password += std::rand() % (126 - 33 + 1) + 33;
    }
    
    return password;
}

int main() {
    std::string password = generatePassword(10);

    std::cout << password << std::endl;
}


 
 
/*
run:
 
g%wn\b|-W4

*/

 



answered Dec 22, 2024 by avibootz

Related questions

2 answers 129 views
129 views asked Dec 21, 2024 by avibootz
1 answer 107 views
1 answer 108 views
1 answer 95 views
1 answer 100 views
100 views asked Dec 22, 2024 by avibootz
1 answer 104 views
104 views asked Dec 21, 2024 by avibootz
1 answer 102 views
...