A small question about my loop program

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

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
#include <iostream>
#include <string>
using namespace 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;}
        else if (i == 5){
                             cout << "Try again later";
            break;}
        
        if (password == "bob") {
            cout << "Correct you may enter";
        }
    }
}
Read below vvv
Last edited on
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.

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
#include <iostream>
#include <string>
using namespace 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";
        }
        else if (i < 5){
            cout << "Please try again:";
        }
        else{
            cout << "Try again later";
            break;}
    }
}
Last edited on
manudude03
What is the use of break; after else{}?
break takes you out of whatever while loop you are in.
Topic archived. No new replies allowed.