2

I need help with generating a random string using C++11.

I don't know how to continue with that, if you can help me please.

#include <random>
char * random_string()
{

        static const char alphabet[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    static const MAX_LEN = 32;  //MAX LENGTH OF THE NEW CHAR RETURNED
    int stringLength = sizeof(alphabet)/sizeof(alphabet[0]);

    for (int i = 0; i<=MAX_LEN;i++)
    {
        //now i don't know what i need to do help!
    }

    static const char test[MAX_LEN];

    return test;

}
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
akroma
  • 47
  • 1
  • 1
  • 6

3 Answers3

9

Return a std::string rather than a raw char *. Populate the string as needed to start, and then shuffle it.

For example;

#include <random>
#include <string>

std::string random_string()
{
     std::string str("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");

     std::random_device rd;
     std::mt19937 generator(rd());

     std::shuffle(str.begin(), str.end(), generator);

     return str.substr(0, 32);    // assumes 32 < number of characters in str         
}

If you really need to extract a raw const char * from a std::string use its c_str() member function.

int main()
{
    std::string rstr = random_string();

    some_func_that_needs_const_char_pointer(rstr.c_str());
}
Peter
  • 35,646
  • 4
  • 32
  • 74
  • the return str.substring(0,32); gives me a error: – akroma Dec 26 '17 at 11:38
  • 10
    `shuffle` may not be the correct option here: result string will have no duplicate characters, which possibly is not the requirement. – Gian Paolo Dec 26 '17 at 11:41
  • The string can have dupplicates, btw the substring gives me a error, why? – akroma Dec 26 '17 at 11:43
  • Typo. `substring()` should be `substr()`. Fixed. Yes, this approach does not duplicate characters in the returned string. If you want to allow duplicated characters, look up `std::generate()`. – Peter Dec 26 '17 at 11:56
7
#include <random>
using namespace std;

string generate(int max_length){
    string possible_characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    random_device rd;
    mt19937 engine(rd());
    uniform_int_distribution<> dist(0, possible_characters.size()-1);
    string ret = "";
    for(int i = 0; i < max_length; i++){
        int random_index = dist(engine); //get index between 0 and possible_characters.size()-1
        ret += possible_characters[random_index];
    }
    return ret;
}
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
Ahmed Osama
  • 854
  • 1
  • 8
  • 17
7

Using Mersene Twister 19937 generator and Uniform discrete distribution you can generate random strings from ranges like "A-Z","a-z" or "0-9" easily.

#include <iostream>
#include <string>
#include <random>

using namespace std;
int main() {
    mt19937 generator{random_device{}()};
   //modify range according to your need "A-Z","a-z" or "0-9" or whatever you need.
    uniform_int_distribution<int> distribution{'a', 'z'};

    auto generate_len = 6; //modify length according to your need
    string rand_str(generate_len, '\0');
    for(auto& dis: rand_str)
        dis = distribution(generator);

    cout << "Random string generated : " << rand_str << endl;
}
Haseeb Mir
  • 928
  • 1
  • 13
  • 22
  • How can I include my own characters without range, for example I only want to generate a random string with my custom characters `abc012-_`, do i have to do it like this? `distribution{'a', 'b', 'c', '0', '1', '2', '-', '_'}` – Felierix Jan 27 '22 at 09:51
  • @Felierix no you cannot do like that you have to give range like **A-Z,a-z,0-9** – Haseeb Mir Jan 28 '22 at 11:49
  • Oh so you can do like `distribution{'a', 'z', '0', '9'}` right? – Felierix Feb 01 '22 at 14:26
  • @Felierix no uniform distribution only takes 2 Arguments so it can be either **A-Z** or **0-9** – Haseeb Mir Feb 01 '22 at 14:53
  • @Felierix: To generate a random string with your own custom characters, you need to modify the range of the uniform_int_distribution object to include only the characters you want to use. – Haseeb Mir Mar 03 '23 at 21:50