gpt4 book ai didi

c++ - 随机化字符数组以显示随 secret 码

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:58:05 25 4
gpt4 key购买 nike

我的任务是创建一个将为用户生成安全密码的解决方案。我需要...

  1. 提示用户输入密码的长度,密码的个数特殊字符以及数字的数量。

    然后应使用这些输入随机生成密码。

例如输出:

密码长度是多少? 8

有多少个特殊字符? 2

有多少个数字? 2

您的密码是:aun2$1s#

我的编程水平处于初学者阶段,这是我到目前为止所做的示例

#include <iostream>
#include <algorithm>
using namespace std;

void WorkoutPass(int ,int,int);

int passlength;
int specChar;
int number;


int main()
{
cout << "Enter the length of password: ";
cin >> passlength;


if (passlength > 0)
{
cout << "Enter the amount of special characters: ";
cin >> specChar;
if (specChar > passlength)
{
cout << "Error - invalid value entered is above the length of password";
}
cout << "Enter amount of numbers";
cin >> number;
if (number > passlength)
{
cout << "Error - invalid value entered is above the length of password";
}
WorkoutPass(passlength, specChar, number);

}
else
{
cout << "Error - invalid value entered password must be above zero";
}
return 0;
}


void WorkoutPass(int p, int s, int n)
{
string password;

char alphaBetArray[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
char specCharArray[10] = {'!','£','$','%','&','@','~','#','>','<'};
char numberArray[10] = {'1','2','3','4','5','6','7','8','9','10'};


int numberOfLetters = p - s - n;


char letter;

// generate (numberOfLetters) letters

// each letter generated we add to the string
password += letter;

// Add special characters
// Add numbers



random_shuffle(password.begin(), password.end());

cout << password.c_str() << endl;
}
void DisplayPass()
{

}

最佳答案

有介绍sample您需要将其与您已经准备好的 random_shuffle 一起使用以生成 password:

random_device rd;
mt19937 g(rd());
auto it = sample(cbegin(alphaBetArray), cend(alphaBetArray), begin(password), numberOfLetters, g);

it = sample(cbegin(specCharArray), cend(specCharArray), it, s, g);
sample(cbegin(numberArray), cend(numberArray), it, n, g);

Live Example


一些注意事项:

  1. 您的数组并不全面,编写一个 lambda 来随机生成一个范围内的字符可能是一个更好的选择,您可以使用 generate_n 来做到这一点.
  2. random_shuffle 中被弃用你需要使用 shuffle现在

关于c++ - 随机化字符数组以显示随 secret 码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42112489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com