【问题标题】:Basic Password Generator - How to get different rand(number) when is called基本密码生成器 - 调用时如何获取不同的 rand(number)
【发布时间】:2015-02-09 05:38:29
【问题描述】:

现在的输出是 HHHHHHHHHHHHHHHHHHHH。我希望程序做的是 randomNum 每次通过循环时都有一个不同的值。所以它会像 AacCEe ......然后继续。

#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <time.h>


using namespace std;

int main(){

    srand(time(0));

    cout << "You'r PW is: \t" << endl;
    char abc [] {'A', 'a', 'B' ,'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G', 'g', 'H', 'h', 'I', 'i', 'J', 'j', 'K', 'k'};
    int randomNum =  rand() % 22;

    for(int i = 0; i <20; i++){
        cout << abc[randomNum];
    }
}

【问题讨论】:

  • 请不要使用rand() 系列函数来生成任何实际用作密码的内容。在 Linux 上使用 /dev/random 或在 Windows 上 CryptGenRandom 并请大量扩展您的输出字符字母表。
  • 谢谢,顺便说一句,我只是在测试角色。为什么我不应该使用 rand()?

标签: c++ random std


【解决方案1】:

你在循环之前已经初始化了 randomNum

int randomNum =  rand() % 22;

您应该将代码更改为

    int randomNum;
    for(int i = 0; i <20; i++)
    {
        randomNum =  rand() % 22;
        cout << abc[randomNum];
    }

这应该可行。

目前 randomNum 只获得一个值,并且您在整个循环中使用该值而不改变该值。

【讨论】:

    【解决方案2】:

    在循环中,您有效地打印相同的字符 20 次,我想您的意图是随机选择 20 个不同的字符。查看我的内联评论。

    #include <stdio.h>
    #include <iostream>
    #include <cstdlib>
    #include <time.h>
    
    
    using namespace std;
    
    int main(){
    
        srand(time(0));
    
        cout << "You'r PW is: \t" << endl;
        char abc [] {'A', 'a', 'B' ,'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G', 'g', 'H', 'h', 'I', 'i', 'J', 'j', 'K', 'k'};    
    
        for(int i = 0; i <20; i++){
            cout << abc[rand() % 22]; // look here
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-14
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2012-04-04
      相关资源
      最近更新 更多