欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C语言生成随机字符串(代码实例)

程序员文章站 2022-05-13 16:08:28
C语言生成随机字符串(代码实例) // C语言生成随机字符. // VS2017 15.6.4 #include #...

C语言生成随机字符串(代码实例)

// C语言生成随机字符.  
// VS2017 15.6.4  
  
#include <stdio.h>  
#include <stdlib.h>  
#include <time.h>  
  
const unsigned char allChar[63] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";  
void generateString(unsigned char * dest, unsigned int len);  
  
int main()  
{  
    const unsigned int strlen = 20;  
    unsigned char str[strlen + 1] = {};  
  
    generateString(str, strlen);  
  
    printf("%s\n", str);  
      
    return 0;  
}  
  
void generateString(unsigned char * dest, const unsigned int len)  
{  
    unsigned int cnt, randNo;  
    srand((unsigned int)time(NULL));  
  
    for (cnt = 0; cnt<len; cnt++)  
    {  
        randNo = rand() % 62;  
        *dest = allChar[randNo];  
        dest++;  
    }  
  
    *dest = '\0';  
}