My program is simple password then enter where their is only 5 attempts at getting it right but when I get the password right on the first attempt it ends without displaying that the password was correct only when i add the if statement that I put as a comment will it say its correct on the first try but I was just curious if theres a way to do this without adding this...If theirs no answer its fine I was just wondering
#include <iostream>
#include <string>
usingnamespace std;
int main ()
{
cout << "Please enter your password:";
string password;
int i;
i = 0;
cin >> password;
/*if (password=="bob") {
cout << "Correct you may enter";}*/
while (password != "bob") {
i++;
if (i < 5) {
cout << "Please try again:";
cin >>password;}
elseif (i == 5){
cout << "Try again later";
break;}
if (password == "bob") {
cout << "Correct you may enter";
}
}
}
You have all the code there, if you just restructure it slightly, you can remove the commented out code:
The reason you need that if statement is the code never enters the loop if the password is right the first time, if you move some lines about, you can shorten the code slightly and avoid the first if statement.
#include <iostream>
#include <string>
usingnamespace std;
int main ()
{
string password;
int i;
i = 0;
while (password != "bob") {
i++;
cout << "Please enter your password:";
// move line above outside while loop to display once only
cin >> password;
if (password == "bob") {
cout << "Correct you may enter";
}
elseif (i < 5){
cout << "Please try again:";
}
else{
cout << "Try again later";
break;}
}
}