C++密码验证程序问题:实现密码错误时的重新输入功能
C++密码验证程序修复与重新输入功能实现
原代码存在的问题
verify_password函数未接收密码参数,无法访问main函数中的password变量- 函数缺少
return true分支,逻辑不完整 userName定义为char类型,仅能存储单个字符,不符合用户名实际需求- 未实现密码无效时重新输入的循环逻辑
- 变量名拼写错误:
lenght应为length - 使用
cin >> password存在缓冲区溢出风险,输入长度超过数组定义上限时会出错
修复后的完整代码
#include <ctype.h> #include <stdbool.h> #include <string.h> #include <iostream> using namespace std; bool verify_password(const char* password); int main() { char userName[50]; char password[16]; // 15个字符+结束符'\0' cout << "\n\t\t\t\tEnter User Name: "; cin.getline(userName, sizeof(userName)); while (true) { cout << "\n\t\t\t\tEnter Password: "; cin.getline(password, sizeof(password)); bool result = verify_password(password); if (result) { cout << "Verified password\n"; break; } else { cout << "Invalid password, please re-enter.\n"; cout << "Password requirements:\n"; cout << "- Length between 8-15 characters\n"; cout << "- Contain at least one uppercase letter\n"; cout << "- Contain at least one lowercase letter\n"; cout << "- Contain at least one digit\n"; cout << "- Contain at least one symbol\n"; } } system("pause>0"); } bool verify_password(const char* password) { int length = strlen(password); if (length < 8 || length > 15) { return false; } bool has_upper = false; bool has_lower = false; bool has_symbol = false; bool has_digit = false; for (int i = 0; i < length; i++) { if (isupper(static_cast<unsigned char>(password[i]))) { has_upper = true; } if (islower(static_cast<unsigned char>(password[i]))) { has_lower = true; } if (isdigit(static_cast<unsigned char>(password[i]))) { has_digit = true; } if (ispunct(static_cast<unsigned char>(password[i]))) { has_symbol = true; } } return has_upper && has_lower && has_digit && has_symbol; }
关键修复说明
- 参数传递:给
verify_password添加const char* password参数,让函数能接收并验证输入的密码 - 循环输入逻辑:用
while(true)循环包裹密码输入和验证逻辑,直到密码验证通过才break退出循环 - 输入安全性:改用
cin.getline读取用户名和密码,避免缓冲区溢出,同时支持带空格的输入 - 完善函数逻辑:
verify_password直接返回所有验证条件的与结果,确保逻辑完整 - 类型转换:调用
isupper等字符判断函数时,将char转为unsigned char,避免处理负数时的未定义行为 - 提示优化:密码无效时输出具体规则要求,帮助用户修正输入
内容的提问来源于stack exchange,提问作者user14070172
相关产品推荐
相关产品推荐

