要求:密码由大写字母、小写字母和数字三种符号组成,并且大写字母、小写字母和数字必须都有。
#include "stdafx.h" #include <ctime> #include <iostream> using namespace std; const int AVAILABLE_CHAR_COUNT = 62; //常量 const char g_availablechar[AVAILABLE_CHAR_COUNT] ={ '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', '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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; //生成密码函数 char * getRandomStringPwd(int length) { if (length < 0) { return 0; } char *pwd = new char[length + 1]; srand(time(NULL)); //初始化为系统时间,在短时间内生成的密码应该是一样的。 for (int i = 0; i < length; ++i) { int randomNum = rand() % AVAILABLE_CHAR_COUNT;//生成0-61之间的随机数 pwd[i] = g_availablechar[randomNum]; } pwd[length] = '\0'; return pwd;//返回堆上指针pwd } //判断密码是否符合需求,有大写、小写、数字 bool isPwdCorrect(char * pwd) { bool isHasLower = false; bool isHasUpper = false; bool isHasNum = false; if (pwd != NULL) { for (int i = 0; pwd[i] != '\0'; ++i) { if (pwd[i] >= 'A' && pwd[i] <= 'Z') { isHasUpper = true; } if (pwd[i] >= 'a' && pwd[i] <= 'z') { isHasLower = true; } if (pwd[i] >= '0' && pwd[i] <= '9') { isHasNum = true; } } } return (isHasNum && isHasUpper && isHasLower); } //获取正确的随机密码 char *getCorrectPwd(int length) { char *pwd = getRandomStringPwd(length); while (!isPwdCorrect(pwd)) { if (pwd != NULL) { delete pwd; pwd = NULL; } pwd = getRandomStringPwd(length); } return pwd; } int main() { char * pwd = getCorrectPwd(6); cout << pwd <<endl; delete pwd; //一定要记得delete return 0; }