mercredi 7 avril 2021

How to randomly generate a string each iteration?

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.




Aucun commentaire:

Enregistrer un commentaire