patterncppMinor
Console random password generator
Viewed 0 times
randomconsolegeneratorpassword
Problem
This program is a random password generator. It asks the user how many chars they want their password to be and how many passwords it should generate.
I used the
I used dynamic allocation to create a
Please give me advice on how I can improve or what I can do differently!
I used the
rand() and srand() methods to generate random letters. I used dynamic allocation to create a
char array based on user input. The comment line is where I tried to dynamically allocate an array of pointers, where each pointer would point to a char array, but I couldn't figure out how to do it so I used a counter and a do while loop and a for loop to create passwords based on user input.Please give me advice on how I can improve or what I can do differently!
#include
#include
#include
#include
const int MAX = 90;
const int MIN = 65;
char * createPassword();
int main()
{
char * p = createPassword();
return 0;
}
char * createPassword()
{
unsigned seed = time(0);
srand(seed);
char x = ' ';
int passwordLength = 0;
int numOfPasswords = 0;
std::cout > passwordLength;
char * pwptr = new char[passwordLength];
std::cout > numOfPasswords;
//char * passwords = new char *pwptr[numOfPasswords];
int passwordcount = 0;
do{
for(int cnt = 0; cnt < passwordLength; cnt++)
{
x = (rand() % (MAX - MIN + 1)) + MIN;
pwptr[cnt] = x;
std::cout << pwptr[cnt];
}
std::cout << std::endl;
passwordcount++;
} while(passwordcount != numOfPasswords);
return pwptr;
}Solution
A few things immediately jump out:
-
Your createPassword` function does two things:
Split the logic into 2 functions.
- Use
std::stringinstead ofchar*.
- Your string is not null terminated (use of
std::stringfixes this)
- Don't create two globals when they're only used in one place.
- Don't create globals with an "uppercase" name. By common practice this is reserved for macros.
srand()andrand()are superseded by any RNG from the `header.
- Don't use a do
...whilewhen afor-loop does the same job more succinctly.
-
Your createPassword` function does two things:
- It communicates with the user.
- It creates a new password.
Split the logic into 2 functions.
Context
StackExchange Code Review Q#87885, answer score: 4
Revisions (0)
No revisions yet.