Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do while loop with nested if statements not exiting in c++

Tags:

c++

OKay, so I'm new to the whole do while loop thing, and I'm trying to make a main menu, here's my code below:

int main()
{
    int choice;
    char sure;
    bool quit = false;
    char ctrl;

    do
    {
        cout << "Main Menu." << endl
             << "1. New Game." << endl
             << "2. Load Game." << endl
             << "3. Exit." << endl
             << "Your choice: ";
        cin >> choice;

        if (choice == 1)
        {
            cout << "Are you sure you wish to start a new game? (Y/N) ";
            cin >> sure;

            if (sure != 'N' || sure != 'n')
            {
                ctrl = 'a';
                quit = true;
            }
        }
        else if ( choice == 2)
        {
            ctrl = 'b';
            quit = true;
        }
        else
            quit = true;

        }
    }
    while (quit == true);

    if (ctrl = 'a')
         cout << "New Game." << endl;
    else if (ctrl = 'b')
         cout << "Load Game." << endl;
    else
         cout << "Goodbye." << endl;

    return 0;
}

there are a few getchar() thrown in there. But the only problem is as you'll probably figure out is that after I do everything it just restarts again, and not exit the loop. What is the problem in the code?

Thanks

like image 540
user1079559 Avatar asked Jan 18 '26 09:01

user1079559


1 Answers

I think you meant while (quit != true);

And remember, comparison is done with ==, if (ctrl = 'a') assigns 'a' to ctrl..

like image 86
Karoly Horvath Avatar answered Jan 20 '26 21:01

Karoly Horvath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!