我对它如何使用错误行的数据感到非常惊讶

问题描述 投票:0回答:1

这是我项目的一些登录代码。该文件包含用户的用户名、密码、电子邮件、地址和电话号码 按照这个顺序。 代码读取文件并获取每一行数据并将其存储在一个结构中,然后将该结构存储在一个向量中。 然后要求用户输入他们的用户名和密码。该程序会根据向量中存储的结构检查这一点,如果它们匹配,则登录用户。 但是我有一个问题,由于某种原因代码正在获取第一行的用户名和密码,但在第二行它使用第一行的一些数据和第二行的一些数据。

下面是代码

struct CargoAccData
{
    string email;
    string address;
    string username;
    string password;
    string phoneNumber;
};


void LogInSystem::LogInCargo() {
    string fileName = "cargoAccount.txt";
    ifstream cargoAccFile(fileName);
    Validation val;
    string attemptedUsername;
    string attemptedPassword;
    bool loopControl = true;
    int count = 0;
    if (cargoAccFile.is_open())
    {
        string line;
        while (!cargoAccFile.eof())
        {
            getline(cargoAccFile, line);
            count++;
        }
    }
    cargoAccFile.close();
    ifstream cargoAccFile2(fileName);
    std::vector<CargoAccData> accounts;
    while (loopControl)
    {
        if (!cargoAccFile2)
        {
            cout << "This file doesn't exist \n";
            loopControl = false;
        }
        for (size_t i = 0; i < count; i++)
        {
            CargoAccData account;
            cargoAccFile2 >> account.email >> account.address >> account.username >> account.password >> account.phoneNumber;
            accounts.push_back(account);
        }
        cout << "Please Enter your Username: \n";
        cin >> attemptedUsername;
        cout << "\nPlease Enter Your Password: \n";
        cin >> attemptedPassword;
        int z = 0;
        bool isCorrect = false;
        while (z < count)
        {
            cout << accounts[z].username << endl;
            cout << accounts[z].password << endl;
            if (attemptedUsername == accounts[z].username && attemptedPassword == accounts[z].password)
            {
                cout << "Welcome to the E-market {" << attemptedUsername << "}!" << endl;
                loopControl = false;
                isCorrect = true;
                break;
            }
            else`your text`
            {
                z++;
            }
        }
        if (isCorrect == true)
        {
            // This is where the main profile will lead to
        }
        else
        {
            cout << "Username or password incorrect, Try Again" << endl;
        }
    }

}

下面是文件内容-

test test test test test test test test
mrjoeyrules VerySecure1 [email protected] 3 07879652851

This is an image of the CLI outputs

期待登录看到用户名是一条小消息

c++ vector struct file-handling fstream
1个回答
0
投票

第一行有多少个“测试”条目?

你实际上并没有读取一行数据并解析它。您阅读了 5 个条目,然后是接下来的 5 个条目,依此类推。要解决这个问题,要么更正输入中的数据(并且所有输入数据都应该被验证为 heck 因为有时,有人会添加一些额外的东西并最终对您的应用程序做非常糟糕的事情)或者在读取所需数据之间丢弃所有无关数据数据和行尾标记。 可能对你有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.