C++随机生成字符串,亲测可用,简单易懂
话不多说,上代码。蜜汁自信注释写的很清楚,嘿嘿。第一次写文章,希望能够对大家有一丢丢的帮助吧~
#include <iostream>
using namespace std;
string rand_str(const int len) /*参数为字符串的长度*/
{
/*初始化*/
string str; /*声明用来保存随机字符串的str*/
char c; /*声明字符c,用来保存随机生成的字符*/
int idx; /*用来循环的变量*/
/*循环向字符串中添加随机生成的字符*/
for(idx = 0;idx < len;idx ++)
{
/*rand()%26是取余,余数为0~25加上'a',就是字母a~z,详见asc码表*/
c = 'a' + rand()%26;
str.push_back(c); /*push_back()是string类尾插函数。这里插入随机字符c*/
}
return str; /*返回生成的随机字符串*/
}
int main()
{
/*测试函数*/
string str; /*声明字符串*/
str = rand_str(20); /*调用函数 输入字符串长度*/
cout << str << endl; /*输出字符串*/
return 0;
}