Do While loop breaks after incorrect input?

Posted by Daminkz on Stack Overflow See other posts from Stack Overflow or by Daminkz
Published on 2010-05-10T19:15:51Z Indexed on 2010/05/10 19:34 UTC
Read the original article Hit count: 169

Filed under:

I am trying to have a loop continue to prompt the user for an option. When I get a string of characters instead of an int, the program loops indefinitely. I have tried setting the variable result to NULL, clearing the input stream, and have enclosed in try{}catch blocks (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;
}

© Stack Overflow or respective owner

Related posts about c++