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

C++登录验证问题:仅读取首个凭证,其他用户无法登录

问题分析

你的登录代码仅读取了文件中的第一组账号密码记录,没有遍历整个文件的所有用户凭证,因此只有第一个用户能匹配成功,其他用户无法完成登录验证。

解决方案

修改登录逻辑,通过循环遍历文件中的每一条记录,直到找到匹配的凭证或文件读取完毕:

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main() {
    ifstream InputFile("record.txt");
    if (!InputFile.is_open()) {
        cout << "无法打开记录文件" << endl;
        return 1;
    }

    string ACN, Pass_word;
    cout << "\n\nEnter Account Number to Login\n\n";
    cin >> ACN;
    cout << "\n\nEnter Password to login\n\n";
    cin >> Pass_word;

    bool loginSuccess = false;
    string Account_Number, Password;
    // 循环读取每一组账号密码,直到文件结束
    while (InputFile >> Account_Number >> Password) {
        if (Account_Number == ACN && Password == Pass_word) {
            loginSuccess = true;
            break; // 找到匹配项,跳出循环
        }
    }

    if (loginSuccess) {
        cout << "\nWelcome Back" << endl;
    } else {
        cout << "\nLogin Error, Please Create Account or check credentials" << endl;
    }

    InputFile.close();
    return 0;
}
额外注意事项
  • 文件写入规范:确保写入record.txt时,每个用户的账号和密码单独占一行(用空格分隔),避免读取时混淆多个用户的信息。示例写入代码:
    ofstream RecordFile("record.txt", ios_base::app);
    if (RecordFile.is_open()) {
        RecordFile << Account_Number << " " << Password << endl;
        RecordFile.close();
    }
    
  • 错误处理:添加文件打开失败的判断,避免因文件不存在或权限问题导致程序异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 11:04:57