C++ 随机生成由大小写字母和数字组成的字符串
头文件
#include <time.h> //秒
#include <sys/timeb.h> //毫秒
1 std::string GetRandomStr(int len) { 2 //毫秒 3 struct timeb time_seed; 4 ftime(&time_seed); 5 srand(time_seed.time * 1000 + time_seed.millitm); 6 7 //秒 8 //srand(time(0)); 9 10 std::string random_str(""); 11 for (int i = 0; i < len; ++i) { 12 switch (rand() % 3) { 13 case 1: 14 random_str += ('A' + rand() % 26); 15 break; 16 case 2: 17 random_str += ('a' + rand() % 26); 18 break; 19 default: 20 random_str += ('0' + rand() % 10); 21 break; 22 } 23 } 24 25 return random_str; 26 } 27