0

当我运行我的程序时,用户可以登录,但是如果输入错误的用户名,它会再次运行检查用户名循环,说他们没有输入有效的用户名。除了一件事之外,这项工作非常好。假设他们尝试登录三次,第三次尝试正确,并提示输入密码。一旦他们输入它,它就会要求输入第二个密码,然后再输入第三个密码。似乎它正在完成其他尝试的功能。我想不出一种方法来检查这一点。有任何想法吗。

UserCheck如果您查看它,您会看到我正在调用getNameIndex. 我几乎肯定这是发生错误的地方。

检查用户的功能:

void User_Psw::UserCheck()
{
    // read from the database
    ifstream fin("dataBase.txt", ios::in);

    if( !fin.good() )
    {
        cout << "Failed to open database file." << endl;
        return;
    }

    while (fin >> username >> password)
    {
        Usernames.push_back(username);
        Password.push_back(password);
        ++sizeOfDatabase; // This may or may not be needed elsewhere.
    }

    // rest of the program
    cout << "Username: ";
    cin >> username;

    getNameIndex();

    cout << "Password: ";
    cin >> password;

    if(!PasswordMatches())
    {
        cout << "Access denied";
    }
    else
    {
        cout << "Success! You have logged in.";
    }
}

这是用户名检查功能

void User_Psw::getNameIndex()
{
    userThere = false;

    for(int i=0; i < sizeOfDatabase; i++)
    {
        if (Usernames[i] == username)
        {
            index = i;
            userThere = true;
        }
    }
    if (userThere == false)
    {
        cout << "\nThat user name does not exsist. \n";
        cout << "Please try again. \n\n";
        UserCheck();
    }
}
4

1 回答 1

1

您的程序结构错误。

Instead of getNameIndex calling UserCheck() again, you should have getNameIndex return a bool - true on success, false on failure. Run it inside of a loop, something like this:

bool success = false;

while (!success)
{
 cout << "Username: ";
 cin >> username;

 success = getNameIndex();
}

Also, instead of having global variables, you should pass them to the function. Something like:

success = getNameIndex(username);

and getNameIndex() shouldn't do any I/O - the function that calls getNameIndex() should also be responsible for printing the error message. Imagine if you used getNameIndex() in a different context, such as when when the program is being run by another program or in an automated way - then printing to the console would be meaningless.

于 2013-02-10T04:58:54.780 回答