在C ++ 11中生成一个随机字符串?

时间:2017-12-26 11:18:17

标签: c++ c++11

我需要帮助使用C ++ 11生成随机字符串。

如果你能帮助我,我不知道如何继续这样做。

#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;

}

3 个答案:

答案 0 :(得分:2)

返回std::string而不是原始char *。根据需要填充字符串以启动,然后将其随机播放。

例如;

#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         
}

如果您确实需要从const char *中提取原始std::string,请使用其c_str()成员函数。

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

    some_func_that_needs_const_char_pointer(rstr.c_str());
}

答案 1 :(得分:2)

#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;
}

答案 2 :(得分:1)

使用Mersene Twister 19937 generatorUniform discrete distribution,您可以轻松地从“A-Z”,“a-z”或“0-9”等范围生成随机字符串。

#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;
}