0

I have a switch statement (copied in below) with cases and a default function, but if I enter a string, the code loops endlessly. How can I prevent this? Do I need to move something outside of the do loop? Use a different loop? I'm new to c++ and don't know how I can fix this, despite having tried moving things out of the loop.

void menu() //Opens new function, called menu, which will contain all code for the menu screen.
{
    cout << setw(60); //Sets the screen width to 60 in order to centre all outputted text on the menu screen.
    std::string text; //Declares the variable "text" as a string.

    int choice{}; //Declares an integer "choice" that will contain the menu input.
    int choicex{}; //Declares an integer "choicex" that will contain the input that will determine virus activation.

    bool valid_input = false;

    cout << setw(60);
    cout << "ARES" << endl;
    cout << setw(61);
    std::cout << "MENU\n";
    cout << setw(78);
    std::cout << "Select one of the following options:\n";
    cout << setw(67);
    std::cout << "1. Activate Virus\n";
    cout << setw(70);
    std::cout << "2. Program Information\n";
    cout << setw(62);
    std::cout << "3. Exit\n";

    do
    {


        std::cin >> choice;

        switch (choice)
        {

        case 1:

            system("CLS");
            cout << setw(84);

            std::cout << "Are you sure? Press 1 to continue, or 2 to go back."; // Prints the spaces

            std::cin >> choicex;

            if (choicex == 1)
            {
                system("CLS");
                Ares();
            }
            if (choicex == 2)
            {
                system("CLS");
                menu();
            }
            if (choicex != 1 and choicex != 2)
            {
                system("CLS");
                cout << setw(80);
                std::cout << "Invalid Input. Redirecting to menu.\n";
                cout << setw(90);
                system("pause");
                system("CLS");
                menu();
            }

        case 2:


            ProgramInfo();


        case 3:

            system("CLS");
            exit(EXIT_FAILURE);


        default:
            system("CLS");
            cout << setw(60);
            std::cout << "Invalid input.\n";
            cout << setw(66);
            std::cout << "Redirecting to menu.\n";
            cout << setw(70);
            std::cout << "Press any key to continue.\n";
            std::cin.ignore();
            system("CLS");
            menu();

        }
        

    }

    
    while (choice < 1 or choice > 3);
}
Dom
  • 7
  • 3

0 Answers0