C++密码生成器如何将数字、大小写字母随机打乱混合输出?
密码生成器代码修改方案
现有代码问题
你当前的写法是按顺序分别循环输出数字、小写字母、大写字母,会导致所有同类型字符连续排列,无法满足随机混合、避免同类型连续的需求。
修改思路
- 首先增加输入合法性校验,确保三类字符数量总和等于你设定的密码总长度
- 先把生成的所有符合数量要求的字符存入临时容器,而非直接输出
- 对容器内的字符做随机打乱
- 增加连续同类型检测逻辑,若出现连续同类字符就重新打乱,直到满足规则
- 最后输出符合要求的密码
修改后完整代码
#include <iostream> #include <ctime> #include <vector> #include <algorithm> #include <cctype> using namespace std; const char num[] = "0123456789"; const char lower_alp[] = "abcdefghijklmnopqrstuvwxyz"; const char higher_alp[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int sizeofnum = sizeof(num) - 1; int sizeoflower_alp = sizeof(lower_alp) - 1; int sizeofhigher_alp = sizeof(higher_alp) - 1; int main() { int password_length = 0, nums, loweralp, higheralp; cout << "Enter password length: "; cin >> password_length; cout << "How many lower alphabet symbols do you want in the password:"; cin >> loweralp; cout << "How many higher alphabet symbols do you want in the password:"; cin >> higheralp; cout << "How many numbers do you want in the password:"; cin >> nums; // 输入合法性校验 if (nums + loweralp + higheralp != password_length) { cout << "Error: The sum of three types of characters is not equal to the password length!" << endl; return 1; } srand(time(NULL)); vector<char> pwd_container; // 生成对应数量的各类字符存入容器 for (int i = 0; i < nums; i++) { pwd_container.push_back(num[rand() % sizeofnum]); } for (int la = 0; la < loweralp; la++) { pwd_container.push_back(lower_alp[rand() % sizeoflower_alp]); } for (int ha = 0; ha < higheralp; ha++) { pwd_container.push_back(higher_alp[rand() % sizeofhigher_alp]); } // 打乱并校验连续同类型 bool is_valid = false; while (!is_valid) { random_shuffle(pwd_container.begin(), pwd_container.end()); is_valid = true; for (int i = 1; i < pwd_container.size(); i++) { // 判断前后字符是否为同类型 bool prev_num = isdigit(pwd_container[i-1]); bool prev_lower = islower(pwd_container[i-1]); bool curr_num = isdigit(pwd_container[i]); bool curr_lower = islower(pwd_container[i]); if ((prev_num && curr_num) || (prev_lower && curr_lower) || (!prev_num && !prev_lower && !curr_num && !curr_lower)) { is_valid = false; break; } } } // 输出最终密码 for (char c : pwd_container) { cout << c; } cout << endl; return 0; }
补充说明
如果某一类字符的数量远超过其他两类,比如10位密码里要求8个数字,逻辑上不可能做到没有连续同类型字符,程序会进入死循环,你可以根据需求增加最大重试次数的限制,避免这种情况。
内容的提问来源于stack exchange,提问作者averagestudent
相关产品推荐
相关产品推荐

