You’re getting only numbers because there’s no specialization of std::to_string()
for char
. So when you do to_string(alphabet[random]))
, it converts the char
to int
(which returns the letter’s character code) and then converts that to a string. So to_string('a')
is "97"
, not "a"
.
Instead of an array, you could use a string containing the alphabet. std::string::append()
allows you to specify a substring to copy from. So you can do:
string alphabet = "abcdefghijklmnopqrstuvwxyz";
int random = rand() % alphabet.size();
password.append(alphabet, random, 1);
This also explains why your password isn’t the desired length. When it intends to append a character, it’s instead appending 2 or 3 digit numbers.
Finally, you’re not clearing password
each time you want to generate a new password, so you’re appending to the old password. The simple solution to this is to move the string password;
declaration inside the first for
loop.
You should also call srand(time())
at the beginning of your program, so you’ll get different passwords every time you run it. Otherwise the program always starts with the same random seed.
0
solved generate random password [C++]