這里的每個數字被選取的幾率大於每個字母被選取的幾率,但小寫字母、大寫字母、數字三類的幾率一樣,
要改善這個問題我覺得可以開一個62大小的字符數組,然后隨機數直接mod62填寫該下標對應的字符
#include <iostream> #include <stdlib.h> #include <time.h> using namespace std; char *randstr(char *str, const int len) { srand(time(NULL)); int i; for (i = 0; i < len; ++i) { switch ((rand() % 3)) { case 1: str[i] = 'A' + rand() % 26; break; case 2: str[i] = 'a' + rand() % 26; break; default: str[i] = '0' + rand() % 10; break; } } str[++i] = '\0'; return str; } int main(void) { char name[20]; cout << randstr(name, 8) << endl; system("pause"); return 0; }