문제

I have made this function to have a simple login using a password. When I press the right password on first attempt it works, and then it also works as expected, when I use all my attempts. But if I make the password wrong in the first attempt, it won't accept the right password on second and third attempt.

Here's the code:

void login(string password)
{
    string input;
    int loginAttempt = 0;
    int RightPassword = 0;

    cout << "Hello! To use the Home Automation System, please login." << endl;

    while (RightPassword == 0)
    {
        cout << "\nEnter your user password: ";
        char temp;
        while(true) /* Infinite loop, exited when RETURN is pressed */
        {
            temp = getch(); /* Get the current character of the password */
            if (GetAsyncKeyState(VK_RETURN))
            {
                break;
            }
            input += temp;
            cout << '\01'; /* Print a smiley */
        }
        for (int i = 0; i <= input.length(); i++)
        {
            if (input[i] != password[i])
            {
                ++loginAttempt;
                cout << "\nWrong password, " << 3 - loginAttempt << " attempts left." << endl;
                break;
            }
            RightPassword = 1;

        }   
        if (loginAttempt == 3)
        {
            cout << "Too many login attempts! The program will now terminate.";
            exit(1);
        }
        cin.clear();
    }
    system("CLS");
    cout << "Welcome user! Thank you for logging in.\n";
} 

I also want to have a way to use backspace to delete the previous char, instead of counting as a char, when I type in the password. Could you help with this too?

Thanks a lot in advance!

도움이 되었습니까?

해결책

string input is never cleared and therefore is constantly being added to

so input is ending up being something like: badpasswordcorrectpasswordreallycorrectpassword

To fix simply clear input on every attempt

http://www.cplusplus.com/reference/string/string/clear/

다른 팁

It doesn't appear that you're resetting your "input" variable after a failed attempt. This means all your previous attempts are being stored in "input" and affecting your password checks in the future. Add something like

input = "";

after you detect a failed password.

write input=""; right after you cout<<"Please enter a password";

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top