我正在尝试循环继续提示用户选择。当我得到一串字符而不是int时,程序无限循环。我已经尝试将变量result设置为NULL,清除输入流,并将其包含在try {} catch块中(不在此示例中)。任何人都可以向我解释为什么会这样吗?
#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;
}
答案 0 :(得分:2)
这里看起来有一个随机元素,因为result
未初始化。
无论如何,直接测试cin
if ( cin && result < options.size() )
并在无效输入时重置它,以便它再次执行I / O操作
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