Search Results

Search found 1 results on 1 pages for 'daminkz'.

Page 1/1 | 1 

  • Do While loop breaks after incorrect input?

    - by Daminkz
    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; }

    Read the article

1