如何使用C语言生成随机字符串?

3

我想在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;
}

除了使用std :: string之外,它可以回答你的问题:https://dev59.com/UXRC5IYBdhLWcg3wAcQ3#440240 - Bill Lynch
1个回答

2
一个简单的方法是定义一个包含在随机字符串中接受的所有字符的字符串,然后重复从该字符串中随机选择一个元素。
#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。

strlen(ALLOWED) -> sizeof(ALLOWED) - 1 - Lundin
我已经更新了我的回答。更普遍的说,有没有一种情况sizeof不能使用而strlen是正确的选择? - Silverspur
1
如果字符串是在运行时分配的或者你只有一个指向它的指针,那么你必须使用 strlen。但是如果长度在编译时已知且字符串不会改变,那么使用 strlen 只会浪费时间。 - Lundin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接