- Well done coming up with a working program and showing your code to the world with the intention to improve! I will tell you some things I would do differently:
- Always indent your code!
- Don't be afraid to leave blank lines in order to group statements
- You are missing the return type of the main function
- Use descriptive variable names (self-documenting code)
- Most people put whitespaces before and after operators
- You do not need to separate strings or
\n when streaming
- You can stop loops with the
break keyword
- You do not need the
if (i == 5) i++;
- Instead of misusing
i as a status, you should either use an enum for multiple status or a clearly named variable, so that other coders can understand your intentions easily
- Have your editor auto-remove trailing whitespaces
- For a password check, you can use an early return, if the password was not correct. If the password was correct, the program flow will continue
- Remember that your program is not cryptographically secure. Passwords should never be hard-coded and never be stored in plain-text. However, since you seem to be a beginner, that's not really important right now :)
- I observed Bash not putting a newline after a program exits, so I recommend writing
std::endl at the end of execution, so the next commandline input prompt does not get added to the end of your program's last line of output.
#include <iostream>
using namespace std;
int main()
{
string correctPassword = "Hello";
bool loginSuccessful = false;
string userInput;
cout << "Please enter your password: ";
for (int i = 1; i <= 5; i++)
{
cin >> userInput;
if (userInput == correctPassword)
{
loginSuccessful = true;
break;
} else {
cout << "wrong password\nplease try again: ";
}
if (i == 4)
cout << "\n\nwarning, you have one try left: ";
}
if (!loginSuccessful)
{
cout << "\n\nyou failed to log in, please leave" << endl;
return 0;
}
cout << "\n\ncorrect !! welcome to the programe :D !!";
return 0;
}