首页 > 解决方案 > 如何用 C 创建一个随机字符串?

问题描述

我想在 C 中生成一个随机字符串。

我要生成的地方<HERE>在代码中。

#include <stdio.h>
#include <string.h>

int main(int argc, char * argv[]) {
    
    if (argc == 2) {
        printf("Checking key: %s\n", argv[1]);
        if (strcmp(argv[1], "AAAA-<HERE>") == 0) {
            printf("\033[0;32mOK\033[0m\n");
            return 0;
        } else {
            printf("\033[0;31mWrong.\033[0m\n");
            return 1;
        }
    } else {
        printf("USAGE: ./main <KEY>\n");
        return 1;
    }
    return 0;
}

标签: c

解决方案


一种简单的方法是定义一个包含您在随机字符串中接受的所有字符的字符串,然后从该字符串中重复选择一个随机元素。

#include <time.h>   // for time()
#include <stdlib.h> // for rand() & srand()

...
srand (time (NULL)); // define a seed for the random number generator
const char ALLOWED[] = "abcdefghijklmnopqrstuvwxyz1234567890";
char random[10+1];
int i = 0;
int c = 0;
int nbAllowed = sizeof(ALLOWED)-1;
for(i=0;i<10;i++) {
    c = rand() % nbAllowed ;
    random[i] = ALLOWED[c];
}
random[10] = '\0';
...

请注意,使用rand()不是生成随机数据的加密安全方式。

编辑:根据 Lundin 评论将 strlen 替换为 sizeof 。


推荐阅读