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

C++新手开发登录注册项目 无法实现登录账号密码校验功能求解答

C++登录校验功能修复方案

问题根因

你注册功能的存储规则是:每个用户信息按「ID→用户名→密码→两个空行」的格式写入UsersInfo.txt,登录功能缺少对应格式的读取、比对逻辑,补全即可实现校验。

修改后的完整Login_System代码

void Login_System() {
    std::string login_id, login_username, login_password;
    std::fstream file;
    system("cls");
    std::cout << "******************************************\n";
    std::cout << "      LOGIN        \n";
    std::cout << "******************************************\n";

    std::cout << "Enter your id: ";
    std::cin >> login_id;
    std::cout << "Enter your username: ";
    std::cin >> login_username;
    std::cout << "Enter your password: ";
    std::cin >> login_password;

    file.open("UsersInfo.txt", std::ios::in);
    if (file.is_open()) {
        std::string stored_id, stored_username, stored_pwd, empty_line;
        bool login_success = false;
        while (std::getline(file, stored_id)) {
            // 跳过文件首尾的空行
            if (stored_id.empty()) continue;
            // 按注册存储顺序读取对应字段
            std::getline(file, stored_username);
            std::getline(file, stored_pwd);
            // 跳过注册写入的两个空行
            std::getline(file, empty_line);
            std::getline(file, empty_line);
            
            // 校验三个字段是否完全匹配
            if (stored_id == login_id && stored_username == login_username && stored_pwd == login_password) {
                login_success = true;
                break;
            }
        }
        file.close();
        
        if (login_success) {
            std::cout << "\n登录成功!按任意键进入系统" << std::endl;
            system("pause>0");
            // 此处添加登录成功后的跳转逻辑,比如进入功能首页
            system("cls");
        } else {
            std::cout << "\n账号、用户名或密码错误,请重试" << std::endl;
            system("pause>0");
            // 可以选择跳转回登录页或者首页
            Login_System();
        }
    } else {
        std::cout << "\n用户数据文件不存在,请先注册账号" << std::endl;
        system("pause>0");
        welcome_screen();
    }
}

额外优化建议

  • 修复注册功能里的拼写错误:将Enter your passowrd修改为Enter your password
  • 若需避免重复注册相同ID,可以在注册写入数据前,参照登录的读取逻辑遍历文件,判断输入的ID是否已存在
  • 生产环境密码不要明文存储,可以简单做哈希加密后再写入文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 06:54:02