How to randomly generate a string each iteration?

Viewed 92

I am wondering how to randomly generate a string per iteration. My code currently generates the same string each iteration. If I type in 3 times, then it will give me the same string 3 times. I want a different and randomly generated string each time.

#include <iostream>
#include <string>
#include <cstdlib>     /* srand, rand */
#include <ctime>
using namespace std;

string RandomString(int len)
{
   string str = "0123456789ABCDEFabcdef";
   string newstr;
   int pos;
   while(newstr.size() != len) {
    pos = ((rand() % (str.size() - 1)));
    newstr += str.substr(pos,1);
   }
   return newstr;
}

int main()
{
   srand(time(NULL));
   string random_str = RandomString(32);
   int user_input;
   
   cout << "Enter how many codes you want: ";
   cin >> user_input;
   for (int i = 0; i < user_input; i++)
   {
   cout << "random_str : " << random_str << endl;
   }

}

Enter how many codes you want: 3 random_str : ae2e8D6C7C04Fb3b83Ec457bcedcC5F5 random_str : ae2e8D6C7C04Fb3b83Ec457bcedcC5F5 random_str : ae2e8D6C7C04Fb3b83Ec457bcedcC5F5

This is my current output. Remember, they all should be different each time.

1 Answers

You need to call the function at every iteration, place it inside the for loop:

int main()
{
    srand(time(NULL));

    int user_input;

    cout << "Enter how many codes you want: ";
    cin >> user_input;
    
    for (int i = 0; i < user_input; i++)
    {
        string random_str = RandomString(32); //<-- here
        cout << "random_str : " << random_str << endl;
    }
}

Using C++ you do have much better random numbers engines, take a look here:

https://en.cppreference.com/w/cpp/numeric/random

Related