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
Vra
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!
Oplossing
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
Ander wenke
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";