如何让用户在菜单选择中重新输入?
我正在尝试创建一个菜单,让用户再次尝试,直到他们输入有效的选择(1-5)。如果用户输入其他内容,我希望它显示错误消息并继续让他们重试。显然我的问题出在我的 while 循环中,但我不确定如何解决这个错误。有人可以帮我重组这段代码吗,谢谢。
#include <cstdlib>
#include <iostream>
using namespace std;
void myList() {
char selection;
cout << "n Select Equipments by category for more details";
cout << "n====================================================";
cout << "n 1 - Gardening Equipment";
cout << "n 2 - Building Equipment";
cout << "n 3 - Decorating Equipment";
cout << "n 4 - Car Maintenance Equipment";
cout << "n 5 - Miscellaneous";
cout << "n X - Exit";
cout << "n Enter selection: ";
// read the input
cin >> selection;
while((selection != 1) || (selection != 2) || (selection != 3) ||
(selection != 4) || (selection != 5)) {
cout << "ERROR: Invalid Key - Try Again: ";
cin >> selection;
cout << endl;
switch(selection)
{
case '1':
system("CLS");
cout << " [GARDENING EQUIPMENT]" << endl
<< " 1.Hoe" << endl
<< " 2.Spade" << endl
<< " 3.Fork" << endl
<< " 4.Shovel" << endl
<< " 5.Rake" << endl
<< " 6.Saw" << endl
<< " 7.Wheelbarrow" << endl;
break;
case '2':
system("CLS");
cout << " [BUILDING EQUIPMENT]" << endl
<< " 1.Rammer" << endl
<< " 2.Crowbar" << endl
<< " 3.Cordless Drill" << endl
<< " 4.Safety Helmet" << endl
<< " 5.Safety Glass" << endl
<< " 6.Spirit Level" << endl
<< " 7.Concrete Mixer" << endl;
break;
case '3':
system("CLS");
cout << " [DECORATING EQUIPMENT]" << endl
<< " 1.Wallpaper Strippers" << endl
<< " 2.Paint rollers" << endl
<< " 3.Protective Sheets" << endl
<< " 4.Paint Trays" << endl
<< " 5.Step Ladder" << endl
<< " 6.Paint Conditioner" << endl
<< " 7.Stanley Knife" << endl;
break;
case '4':
system("CLS");
cout << " [CAR MAINTENANCE EQUIPMENT]" << endl
<< " 1.Extension Bar" << endl
<< " 2.Spark Plug Pilers" << endl
<< " 3.Air Compressor" << endl
<< " 4.Oil drain & caddy" << endl
<< " 5.Engine Hoist" << endl
<< " 6.Brake lathe" << endl
<< " 7.Transmission Jack" << endl;
break;
case '5':
system("CLS");
cout << " [MISCELLANEOUS]" << endl
<< " 1.Cleaning Powder" << endl
<< " 2.Aluminium Foil" << endl
<< " 3.Filter Paper" << endl
<< " 4.Nylon Scrubber" << endl
<< " 5.Floor Duster" << endl
<< " 6.Dettol" << endl
<< " 7.Disposable Garbage Bag" << endl;
break;
case 'X':
case 'x': {
cout << "n To exit the menu";
}
break;
// other than A, M, D and X...
default:
cout << "n Invalid selection";
// no break in the default case
}
cout << "n";
}
}
int main()
{
myList();
return 0;
}
回答
条件(selection != 1) || (selection != 2) || (selection != 3) || (selection != 4) || (selection != 5)withchar selection;将始终为真,因为没有整数同时等于 1 和 2。
您应该使用&&(logical AND) 而不是||(logical OR)。
此外,您可能希望将输入与类似字符'1'而不是整数(字符代码)进行比较1。
总之,条件应该是:
(selection != '1') && (selection != '2') && (selection != '3') && (selection != '4') && (selection != '5')
或者你可能想要更简单的:
selection < '1' || '5' < selection