I am trying to create a random password generator. When I call the function multiple times it returns the same character value. QQpQ;7Q7pQ;p
I have tried adding srand(time(0));
or srand((unsigned int) time(NULL));
in my main function.
Looking at other stack over flow posts I see that srand helps create different characters each time I run the program. However it still returns multiples of the same character.
How can I change srand() seed during run time to get different random numbers?
#include <string>
#include <iostream>
#include <time.h>
using namespace std;
string randomGenerator(int numberOfCharacters);
char randomCapitalCharacter();
char randomLowerCharacter();
char randomSpecialCharacter();
char randomInt();
int main(){
srand((unsigned int) time(NULL));
int passwordLength = 12;
string password = randomGenerator(passwordLength);
cout << password << endl;
return 0;
}
string randomGenerator(int numberOfCharacters){
char randomCharacterTypes[4] = {randomLowerCharacter(),randomInt(), randomCapitalCharacter(), randomSpecialCharacter()};
std::string password;
while (numberOfCharacters > 0){
int random = rand()%4;
password += randomCharacterTypes[random];
numberOfCharacters--;
}
return password;
}
char randomInt(){
std::string numberAsString = to_string(std::rand()% 10);
char randomNumberChar = numberAsString.at(0);
return randomNumberChar;
}
char randomLowerCharacter(){
return 97 + rand()%26; //97 = a
}
char randomCapitalCharacter(){
return 65 + rand()%26; //65 = A
}
char randomSpecialCharacter(){
/** Special characters are split by numbers so we pick a random from one of the 2 groups.*/
return (rand()%2) ? char(33 + rand()%14) : char(58 + rand()%8);
}
randomCharacterTypes[4]
only contains 4 different characters, did you mean to create an array of function pointers? – Alan BirtlesRReR>>eReR6e
and the second time it printsg>g>7gTgg>>T
Is it because you are running it more than once in the same second? That would give the same values because time(NULL) returns an integer number seconds - so if you run it more than once in the same second time(NULL) would return the same value. – Jerry Jeremiah//97 = a
if you write'a'
instead of97
in the code (and similar for other characters).. – molbdnilo