c++ - 带有选项的菜单列表
问题描述
我正在尝试在程序中制作选择列表,现在我对用户输入错误输入时会发生什么感到困惑。
我试过用do loop 来做(我循环了 switch 语句)。另外,尝试将变量键设置为整数和字符,但都有问题。Char只需要一个字符,当你写多个字符时,它会自行检查每个字符。使用int输入错误时 ,我会得到一个无限循环的菜单功能。
另外,尝试在stackoverflow中使用我在这里找到的cin.fail(),但没有成功。
void menu()
{
if(!isEmpty())
{
showStack();
}
else
{
cout << "stekas tuscias!" << endl;
}
cout << "---------------------------" << endl;
cout << "1. Iterpti i steka (push)" << endl;
cout << "2. Pasalinti is steko (pop)" << endl;
cout << "3. Issaugoti steka" << endl;
cout << "4. Issaugoti steka ir uzdaryti programa" << endl;
cout << "---------------------------" << endl;
cout << "Jusu pasirinkimas: ";
char key;
cin >> key;
switch(key)
{
case '1':
{
cout << "Irasykite reiksme i konsole: ";
int data;
cin >> data;
cout << endl;
push(data);
break;
}
case '2':
{
cout << endl;
pop();
break;
}
case '3':
{
write();
cout << "--------" << endl;
cout << "Stekas issaugotas!" << endl;
cout << "--------" << endl;
menu();
break;
}
case '4':
{
write();
break;
}
default:
{
cout << "Tokio pasirinkimo nera!" << endl;
cout << endl;
key = '\0';
menu();
break;
}
}
}
如果需要,我的整个代码:https ://pastebin.com/Xv1HE0Mh
解决方案
我确定为什么 cin.fail() 或 (!cin) 不适合你。但是,你可以这样做。而且,我也确定存在这种问题。
template <class T>
int check (T ch)
{
if (ch >= 'a' && ch <= 'Z') return 0;
else return 1;
}
接着。
main ()
{
.
.
char c;
cin.get (c); //Note here!!
if (check (c)) {...}
else {...} //You can use goto.
.
}
推荐阅读
- r - Bookdown(证明)自定义环境:如何在自定义(例如证明)环境中嵌套代码块或内联 R 并获得正确的解析?
- firebase - 生成具有 github 操作范围的 firebase 令牌
- javascript - ScrollArea 如何滚动到底部
- arrays - 按下回车时停止获取用户输入(C 语言)
- reactjs - 同时在两个输入字段中写入值ReactJS
- python - KivyMD 尝试将小部件(进度条)的实例添加到屏幕
- javascript - 两个如何在 javascript 文件中提及两个 HTML 文件
- javascript - 如何使用Angular将字符串中的特定字符设置为粗体?
- angular9 - 如何将 xml 响应转换为角度 9 中的 xlsx 以下载文件,得到 SyntaxError: Unexpected token P in JSON at position 0
- c# - 使用自定义 Json 反序列化器创建新对象