How to go back to previous line, to retry validating username and password?
Expand the password checking program from earlier in this chapter and make it take multiple
usernames, each with their own password, and ensure that the right username is used for the
right password. Provide the ability to prompt user's again if the first login attempt failed. Think
about how easy (or hard) it is to do this for a lot of usernames and passwords.
From the book Jumping into C++ page 71 Q 4, chapter 4: If Statements.
Here's what I've done so far:
Code:
//Answer to page 71 Q 4
#include <iostream>;
#include <string>;
using namespace std;
int main()
{ string username;
string password;
string choice;
top:
cout << "Username: ";
getline(cin, username, '\n');
cout << "Password: ";
getline( cin, password, '\n');
if ( username == "Johnny" && password == "x" || username == "Debb" && password == "y" || username == "Oh hai" && password == "z")
{ cout << "Valid password. You may now enter paradise.\n"; }
else
{ cout << "Invalid username or password. Please try again.\n If you forgot your password, ask for help at nearby abyss's sinner support.\n\n";
top2:
cout << "Do you want to try filling in the username and password again? y/n \n\n";
cin >> choice;
if ( choice == "y")
{ goto top; }
else if (choice == "n")
{ return 0; }
else
{ cout << "Invalid choice. Choices: y/n. \n\n";
goto top2;
}
}
system("pause");
return 0;
}
My question now is, how do I prompt the user to retry validating their username and password if their previous attempt had failed?
I tried using GOTO, but when it prompt the user the the previous line, the user cannot input their username.
There must be many alternatives to do this.
Please tell me what you know, thanks.
The paradise and abyss part is just a joke. I don't mean to offend anybody. I've never met people go in or out of it though. So I think nobody will be offended. But just in case.
Please do also tell me if there's any flaw in the structure of my code, and which part can be improved. Thank you. :biggrin: