【发布时间】:2015-02-16 04:22:28
【问题描述】:
所以我使用 do while 循环显示一个菜单,如下所示,我希望用户得到菜单提示,直到他们做出有效的选择 - 通过输入数字 1、2、3 或 4。我然后想要使用 switch case 语句来识别用户的选择并执行相关的代码块。但是,在输入验证方面,我如何解释用户输入字母而不是数字?下面的代码成功地继续下一次迭代,在用户输入字母时重新提示,只是它进入了一个连续的循环。
int selection;
do{
cout << "Which option would you like to select? (select 1, 2, or 3)";
cout << "1: Option 1" << endl;
cout << "2: Option 2" << endl;
cout << "3: Option 2" << endl;
if(!(cin >> selection)){
cout << "Please select an integer from 1-4." << endl;
cin.clear()
}
}while(selection != (1) or (2) or (3) or (4));
我尝试使用 istringstream 插入下面的代码,将用户响应从字符串流式传输到 while 循环内的 int 作为尝试解决问题的替代方法,但无济于事。
string temp;
cin >> temp;
clearInputBuffer();
istringstream is(temp);
is >> selection;
更新的代码 - 仍然出现无限循环(仅当用户输入字母时
特点;整数的行为符合预期)
int selection;
do{
cout << "Which option would you like to select? (select 1, 2, or 3)";
cout << "1: Option 1" << endl;
cout << "2: Option 2" << endl;
cout << "3: Option 2" << endl;
if(std::cin >> selection){
cout << "Enter the new price: ";
}
else if(!std::cin.eof()){
cout << "Please select an integer from 1-4." << endl;
cin.clear();
}
}while(selection != 1 && selection != 2 && selection != 3 && selection != 4);
【问题讨论】:
-
我打赌你不知道
selection != (1) or (2) or (3) or (4)是什么意思 -
anything or true始终是true。
标签: c++ while-loop switch-statement cin