0

My code for a main menu isn't functioning correctly. I cant find out why the do while loop repeats forever when the user inputs, a bool is set to true, and it works, but if the user inputs a wrong character, the loop continues forever. and displays "Invalid character. Please try again." and doesn't allow the user to input.

void mainmenu() {
bool wrong = false;
    system("cls");

    cout << "Hello! Welcome to the menu. ";
    cout << "\n\n";
    cout << "What would you like to do?\n";
    cout << "Options:\n";
    cout << "1. Password generator\n";
    int choice{ 0 };
    do {

        cin >> choice;


        if (choice == 1) {
            wrong = true;
            passgen();
            break;
        }

        else {
            cout << "Invalid character. Please try again." << endl;
            cin.clear();
        }
        
    } while (!wrong);
    
    

}

Note- I didnt include the #include in this snippet of code, but the error is within the loop repetition.

  • What stops your `while` loop and do you update it if the user inputs something invalid? – D-RAJ Jan 28 '21 at 19:56

1 Answers1

0

If you want to read a line of input from the user and parse it to see if it's valid, then write code that reads a line and parses it. Your current code only reads integers. So if there's input that isn't an integer, it will never read it and complain about it over and over.

A quick and dirty alternative is to read/ignore a line and throw it away after calling cin.clear().

But I'm a big believer in writing code that does what you actually want to do. You want to read whatever the user inputs, whether it's an integer or not. So why does your code read an integer?

David Schwartz
  • 179,497
  • 17
  • 214
  • 278