[try Beta version]
Not logged in

 
 
A small question about my loop program

Aug 3, 2013 at 8:15pm
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";
        }
    }
}
Aug 3, 2013 at 8:22pm
Read below vvv
Last edited on Aug 3, 2013 at 8:37pm
Aug 3, 2013 at 8:28pm
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 Aug 3, 2013 at 10:30pm
Aug 4, 2013 at 12:49am
manudude03
What is the use of break; after else{}?
Aug 5, 2013 at 1:43pm
break takes you out of whatever while loop you are in.
Topic archived. No new replies allowed.