Do while loop menu

So I'm trying to implement a menu via a do while loop, however I am having a bit of trouble. I can get the "exit" functionality of the menu to work fine, and I may have muddled the coding up a bit but basically my code thus far looks like this:

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
int main()
cout << "Please Choose from the Menu, or press q to quit\n";
    cout << "1. Login\n";
    cout << "2. Quit\n";
    char select = ' ';
    string username;
    string password;
    
    do {
        while(true){
    if(select = 'q' || '2'){
        cin >> select;
        exit(1);
    }
    if(select = '1'){
        cin >> select;
        cout << "Please enter your username\n";
        cin >> username;
        cout << "Please enter your password\n";
        cin >> password;
        if((username == "ZZZ") && (password == "XXX")){
            cout << "Welcome\n";
        }
        else{
            cout << "Incorrect. Please try again\n";
            }
        }
    }
    }while ((select != '1') && (select != '2'));


I thought I had coded so that if the user types '1', the user would go to the login option, but this is not the case. Could someone guide me in the right direction?
Last edited on
You have 2 loops, the do loop is the highest level loop handling the selection but inside that loop you have a while(true) which does not stop unless you use a break, meaning you can't get outside of it. If you want it explained better, you build a house with a room with no doors or exits inside. You can easily get inside the house but once you get inside that room, you can't get out!

The while(true) is a great way to do a loop if you use the keyword break for the exit points. It comes in handy for larger programs when you don't want too many variables and have a few exit points for different scenarios.
Okay, I think I got what you're saying. I've altered the code so it runs more like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
while {
    
    if(select = '1'){
        cout << "Please enter your username\n";
        cin >> username;
        cout << "Please enter your password\n";
        cin >> password;
        if((username == "ZZZ") && (password == "XXX")){
            cout << "Welcome\n";
        }
        else{
            cout << "Incorrect. Please try again\n";
            }
        }
    }
    }while (select != 'q' || 2);


This is an improvement, and more in line with what I'm trying to achieve.
a) Think you meant to place "do" at the start. If not, you'll need a conditional there.
b) Your if uses the assignment operator ('=') instead of the comparison operator ('==').
c) In your first code snippet, you messed up your conditional-chaining. It's "x == a || x == b", not "x == a || b".
Topic archived. No new replies allowed.