0

I want to generate n random passwords which have 3 Uppercase letters, 3 lowercase letters and 2 numbers in it.I used this function to generate a password with 3 Uppercase letters and 3 lowercase letters and when i enter n it always shows me the same password: This is my code:

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
void generatepassword()
{
    srand(time(NULL));
    char a,b,c,d,e,f,g;
    a = static_cast <char>(rand () % 26 + 65);
    b = static_cast <char>(rand () % 26 + 65);
    c = static_cast <char>(rand () % 26 + 65);
    d = static_cast <char>(rand () % 26 + 97);
    e = static_cast <char>(rand () % 26 + 97);
    f = static_cast <char>(rand () % 26 + 97);

    cout<<a<<b<<c<<d<<e<<f<<g<<endl;
}
int main()
{
    int n;
    cin>>n;
    for (int i=1;i<=n;i++)
    {
        generatepassword();
    }
    return 0;
}

How can i make it show different passwords?

Anonymous
  • 31
  • 5

2 Answers2

1

You only need to seed rand once. Seed it at the beginning of your code:

int main()
{
    srand(time(NULL)); //<---
    int n;
    cin>>n;
    for (int i=1;i<=n;i++)
    {
        generatepassword();
    }
    return 0;
}
yizzlez
  • 8,757
  • 4
  • 29
  • 44
0

Please refer to the usage of function srand: http://www.cplusplus.com/reference/cstdlib/srand/

For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand.

Two different initializations with the same seed will generate the same succession of results in subsequent calls to rand.

In your code, the generatepassword() was called so fast that the seed value were all same.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Young
  • 25
  • 5