在C ++ 11中生成一个随机字符串? [英] generate a random string in C++11?
本文介绍了在C ++ 11中生成一个随机字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用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;
}
推荐答案
返回一个 std :: string
而不是原始的 char *
.根据需要填充字符串以开始,然后将其随机播放.
Return a std::string
rather than a raw char *
. Populate the string as needed to start, and then shuffle it.
例如;
#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
}
如果您真的需要从 std :: string
提取原始的 const char *
,请使用其 c_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());
}
这篇关于在C ++ 11中生成一个随机字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文