随机密码生成器相同的字符串

Random password generator same string

这是我的第一个 C 程序,我想随机生成一个密码,但每次 运行 程序都会生成相同的字符串。 (总是生成 "pkDHTxmMR1...")这实际上不会被使用,所以 rand() 的安全性对我来说并不重要。为什么每次我 运行 它都会输出相同的字符串?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>  
//this is a program to generate a random password

int main()
{
    int counter = 0;
    srand(time(NULL));
    char randChar;

    int  passwordLength;

    printf("Type in a password Length \n");
    scanf("%d", &passwordLength);

    while(counter < passwordLength)
    {
        //seed random based on time
        srand(time(NULL));
        randChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[random () % 62];    
        printf("%c", randChar);
        counter++;
    }
    return 0;
}

您的循环不到一秒就可以到达 运行。

因此,time(NULL)总是returns相同的值,所以你的随机数都有相同的种子。

不要那样做。

标准:

The srand function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand. If srand is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated.

您系统上的 time_t 很可能是基于秒或类似的东西。但是 srand() 次调用之间的执行时间远少于一秒,所以你一直给它提供相同的种子值。

在整个程序中始终只调用一次 srand()

哦,亲爱的。在我自己尝试提问者的代码之前,每个人都答错了,包括我。

事实上,是的,在循环中不应该调用 srand(),因为它会在每次迭代时重新播种随机数生成器。但是,也不应在循环外调用 srand(),因为用于生成实际随机数的函数是 random() 而不是 rand()。正确的代码是

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int counter = 0;
    srandom(time(NULL));  // Correct seeding function for random()
    char randChar;

    int  passwordLength;

    printf("Type in a password Length \n");
    scanf("%d", &passwordLength);

    while(counter < passwordLength)
    {
        randChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[random () % 62];
        printf("%c", randChar);
        counter++;
    }
    printf("\n"); // Stops the output from being on the same line as the prompt
    return 0;
}