You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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;
}

关键修复说明

  1. 参数传递:给verify_password添加const char* password参数,让函数能接收并验证输入的密码
  2. 循环输入逻辑:用while(true)循环包裹密码输入和验证逻辑,直到密码验证通过才break退出循环
  3. 输入安全性:改用cin.getline读取用户名和密码,避免缓冲区溢出,同时支持带空格的输入
  4. 完善函数逻辑:verify_password直接返回所有验证条件的与结果,确保逻辑完整
  5. 类型转换:调用isupper等字符判断函数时,将char转为unsigned char,避免处理负数时的未定义行为
  6. 提示优化:密码无效时输出具体规则要求,帮助用户修正输入

内容的提问来源于stack exchange,提问作者user14070172

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 21:54:18