Do While loop breaks after incorrect input?

I'm trying to get the loop to keep prompting the user for an option. When I get a string of characters instead of int, the program chants endlessly. I tried setting the variable to NULL by clearing the input stream and including catch blocks in the try {} (not in this example). Can anyone explain to me why this is?

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int menu(string question, vector<string> options)
{
    int result;

    cout << question << endl;

    for(int i = 0; i < options.size(); i++)
    {
        cout << '[' << i << ']' << options[i] << endl;
    }

    bool ans = false;
    do
    {
        cin >> result;
        cin.ignore(1000, 10);
        if (result < options.size() )
        {
            ans = true;
        }
        else
        {
            cout << "You must enter a valid option." << endl;
            result = NULL;
            ans = false;
        }       
    }
    while(!ans);
    return result;
}

int main()
{
    string menuQuestion = "Welcome to my game. What would you like to do?";
    vector<string> mainMenu;
    mainMenu.push_back("Play Game");
    mainMenu.push_back("Load Game");
    mainMenu.push_back("About");
    mainMenu.push_back("Exit");

    int result = menu(menuQuestion, mainMenu);
    cout << "You entered: " << result << endl;
    return 0;
}

      

+2


a source to share


1 answer


It looks like there is a random element here as it is result

not initialized.

In any case, the test cin

directly

    if ( cin && result < options.size() )

      



and reset on invalid input so that it does I / O again

        result = 0; // inappropriate to initialize an integer with NULL
        cin.clear(); // reset cin to work again
        cin.ignore(1000, '\n'); // use \n instead of ASCII code

      

+2


a source







All Articles