#include <iostream>
#include <ctime>
using namespace std;
string randstr(string strCharElem,int nOutStrLen)
{
string strRet;
strRet.insert(0,nOutStrLen,'\0');
srand((unsigned)time(0));
int iRand = 0;
for (int i = 0; i < nOutStrLen; ++i)
{
iRand = rand() % strCharElem.length();
strRet[i] = strCharElem[iRand];
}
return strRet;
}
int main()
{
string str = randstr("abcdefghigklmnopqrstuvwxyz",5);
cout << "randstr Result:" << endl << str.c_str() << endl;
getchar();
return 0;
}
运行结果:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIyVGduV2QvwVe0lmdhJ3ZvwFM38CXlZHbvN3cpR2Lc1TPB10QGtWUCpEMJ9CXsxWam9CXwADNvwVZ6l2c052bm9CXUJDT1wkNhVzLcRnbvZ2LcZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39TNyQjMwQzMyETNxETM1EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)