Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate a random string in C++11? [duplicate]

Tags:

c++

c++11

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;

}
like image 869
akroma Avatar asked Dec 09 '25 00:12

akroma


2 Answers

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());
}
like image 176
Peter Avatar answered Dec 10 '25 14:12

Peter


#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;
}
like image 36
Ahmed Osama Avatar answered Dec 10 '25 14:12

Ahmed Osama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!