Hello all, this is my first post. I am currently reading a beginner book to learn C++.
The code below is my latest attempt to solve a practice question from the book.
Keep in mind I am less than a week into C++ and have minimal knowledge of variables, conditionals, loops, and functions.
I was simply hoping for a review of my code. Any tips would be helpful. Is my logic correct? etc.
Thanks all!
Code Description:
-This program asks the user to enter a user name and password (which I have already pre-defined in the code).
-It then checks the user's input in the if-else-if statements.
-If the login condition is true, it will print a welcome message to the user.
-Otherwise it will tell the user the entry is invalid and allows them to try 4 more times. (5 in total)
-Also, the loginAttempt loop counter is incremented up by 1.
-All of these if-else-if statements are nested in a while loop which checks the loginAttempt condition.
-When the loop breaks, the program will check to see if the variable loginAttempt == 5, if its true it will tell the user they have tried to login too many times and the program will terminate.
-If the login was successful the loop will break and ignore the the previous condition I just mentioned and print a thank you message for logging in.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
#include <iostream>
using namespace std;
int main ()
{
string userName;
string userPassword;
int loginAttempt = 0;
while (loginAttempt < 5)
{
cout << "Please enter your user name: ";
cin >> userName;
cout << "Please enter your user password: ";
cin >> userPassword;
if (userName == "greg" && userPassword == "dunn")
{
cout << "Welcome Greg!\n";
break;
}
else if (userName == "patrick" && userPassword == "dunn")
{
cout << "Welcome Patrick!\n";
break;
}
else
{
cout << "Invalid login attempt. Please try again.\n" << '\n';
loginAttempt++;
}
}
if (loginAttempt == 5)
{
cout << "Too many login attempts! The program will now terminate.";
return 0;
}
cout << "Thank you for logging in.\n";
}
|