2

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;
}
Charles Ray
  • 470
  • 1
  • 5
  • 16
  • possible duplicate of [While loop with try catch fails at bad cin input](http://stackoverflow.com/questions/2292202/while-loop-with-try-catch-fails-at-bad-cin-input) – kennytm May 10 '10 at 19:19
  • Prefer quoted characters rather than their decimal equivalents. So `cin.ignore(1000,10)` becomes the more readable `cin.ignore(1000, '\n')`. – Thomas Matthews May 10 '10 at 19:24

1 Answers1

2

It looks like there is a random element here, since result is not initialized.

In any case, test cin directly

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

and reset it upon invalid input so it will again perform I/O operations

        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
Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
  • you might be interested in this [stack-exchange proposal](http://area51.stackexchange.com/proposals/11464/code-review?referrer=aWNm_PdciyFqjFW8CUacGw2 "Code Review"). – greatwolf Jan 13 '11 at 08:28