Style suggestion: do not leave so many empty lines. They waste vertical space and some people may find them annoying.
You must remember why you are using a
for() loop.
You are using a
for() loop because you want to limit how many times you read the
password. You want to make sure that the user gets three tries, and no more.
So the obvious first thing to do is to move the reading inside the
for() loop.
1 2 3 4 5
|
for (/* ??? */)
{
cout << "Enter your password: ";
cin >> password;
}
|
The next thing to do is to move the password check inside the
for() loop as well, right after you read it. Because obviously, every time you read a new password you must also check it.
1 2 3 4 5 6 7 8 9 10
|
for (/* ??? */)
{
cout << "Enter your password: ";
cin >> password;
if (password == "freddycakes")
{
/* ??? */
}
}
|
Now we must think about what to write instead of the
/* ??? */
comments.
The one in the
if() is a bit trickier, so I'll help with that. The other one, again you should be able to figure out on your own.
So what if the
password was guessed correctly? Then it means we no longer need to read new passwords to check. We must stop the
for() loop.
This is done by using the
break;
instruction.
1 2 3 4 5 6 7 8 9 10 11
|
for (/* ??? */)
{
cout << "Enter your password: ";
cin >> password;
if (password == "freddycakes")
{
/* ??? */
break;
}
}
|
There's one more thing, we have to remember if the password was guessed correctly or not.
For this we use a
bool flag named
password_was_guessed
. After the
for() loop we check this flag. If it is true, then we print "Correct password", otherwise we print "Incorrect password".
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
bool password_was_guessed = false;
for (/* ??? */)
{
cout << "Enter your password: ";
cin >> password;
if (password == "freddycakes")
{
password_was_guessed = true;
break;
}
}
if (password_was_guessed == true)
{
cout << "Correct password\n";
}
else
{
cout << Incorrect password\n";
}
|