开发者

Do While loop breaks after incorrect input?

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;
    d开发者_JAVA百科o
    {
        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;
}


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜