I added cin.ignore(); after cin.getline. I now can input username and password again after failed the first attempt to validate username and password. However, even if I put the valid password on the second attempt, the username and password is invalid. Why?
And sorry, I don't really understand what you meant by "if fail, retry" approach and "if succeeded, then if succeeded, then... " approach. Could you explain it in more detail, add example code perhaps?
Here's the change I've made:
Code:
//Answer to page 71 Q 4, chapter 4: If Statements
#include <iostream>;
#include <string>;
using namespace std;
int main()
{ string username;
string password;
string choice;
username:
cout << "Username: ";
getline(cin, username, '\n');
cin.ignore();
cout << "Password: ";
getline( cin, password, '\n');
cin.ignore();
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 username; }
else if (choice == "n")
{ return 0; }
else
{ cout << "Invalid choice. Choices: y/n. \n\n";
goto top2;
}
}
system("pause");
return 0;
}