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;
}
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());
}
#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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With