c - 随 secret 码生成器相同的字符串

标签 c random passwords

这是我的第一个 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;
}

最佳答案

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

事实上,是的,在循环中不应该调用 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;
}

关于c - 随 secret 码生成器相同的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30486336/

相关文章:

random - NIST 随机性测试套件返回 igamc :UNDERFLOW for most of the tests

c - 生产者和消费者在数字生成器中没有正确关闭

bash - Bash 中的密码管理

C 将 float 转换为 int 数组

c++ - 无递归初始化

java - 在 Double 域中生成 Double

linux - 如何在apache2中为文件夹提示密码

web - 为什么 Coda 2 不保存 ftp 访问的密码?

c - 如何在 C 中复制数组元素?

c - 在 C 中使用宏和 # 运算符打印空格