如何使用循环显示菜单并重新提示输入
How do I use a loop to display a menu and re-prompt for input?
我想要一个接受用户输入的菜单显示。但是,我希望用户能够回到菜单的开头重新选择选项。
while(end != 1) {
display menu options
prompt user for input
if(input == x) {
do this
}
else
do that
}
然后,我希望它跳回到循环的开始,并再次问这个问题。如果不在屏幕上创建一个无限循环的菜单打印,我该怎么做?
不幸的是,您并没有真正显示您正在使用的代码,而是显示了一些伪代码。因此,很难判断你到底想做什么。然而,从对你的问题和伪代码的描述来看,我怀疑问题的根源是你没有检查你的输入,也没有将流恢复到合理的良好状态!要阅读菜单选择,您可能需要使用类似于以下的代码:
int choice(0);
if (std::cin >> choice) {
deal with the choice of the menu here
}
else if (std::cin.eof()) {
// we failed because there is no further input: bail out!
return;
}
else {
std::string line;
std::cin.clear();
if (std::getline(std::cin, line)) {
std::cout << "the line '" << line << "' couldn't be procssed (ignored)n";
}
else {
throw std::runtime_error("this place should never be reached! giving up");
}
}
这只是输入的大致布局。它可能会被封装到一个函数中(在这种情况下,您可能希望以某种不同的方式从闭合输入中解脱出来,可能使用异常或特殊的返回值)。他的主要部分是
- 使用
std::isteam::clear()
将流恢复到良好状态 - 跳过坏输入,在这种情况下使用具有
std::string
的std::getline()
;你也可以只std::istream::ignore()
行的剩余部分
你的菜单可能还有其他问题,但如果没有看到具体的代码,我想很难判断具体的问题是什么。
与其使用while,不如考虑使用一个函数,这样您就可以在需要的地方调用它:
void f()
{
if(end != 1) {
display menu options
prompt user for input
if(input == x) {
do this
f();
}
else{
do that
f();
}
}
}
我也不确定你在寻找什么,但这是菜单的一些粗略代码
while(1){
cout<<"******* Menu ********n";
cout<<"-- Selections Below --nn";
cout<<"1) Choice 1n";
cout<<"2) Choice 2n";
cout<<"3) Choice 3n";
cout<<"4) Choice 4n";
cout<<"5) Exitn";
cout<<"Enter your choice (1,2,3,4, or 5): ";
cin>>choice;
cin.ignore();
switch(choice){
case 1 :
// Code for whatever you need here
break;
case 2 :
// Code for whatever you need here
break;
case 3 :
// Code for whatever you need here
break;
case 4 :
// Code for whatever you need here
break;
case 5 :
return 0;
}
相关文章:
- 如何使用递归循环我的代码(当用户输入无效输入时,它会再次提示他们)?
- 如何确保用户在一行上提示输入一次时输入名字和姓氏?
- 为什么 std::cin 不提示用户输入?
- 如何使用打印到 PDF 打印机在 MFC 和 CView 中以编程方式打印而不提示输入文件名?
- 编写一个程序,提示用户输入一个整数,然后输出数字的单个数字和数字的总和
- C++:跳过第一个用户输入提示
- (显示金字塔)编写一个程序,该程序提示用户输入1到15的整数并显示金字塔
- 循环不提示用户输入(C )
- C++ 编写一个程序,提示用户以数字形式输入一个人的出生日期(投掷/接球)
- 使用提示用户输入笛卡尔平面中某些点的x-y坐标(浮点类型)的函数
- 如何提示用户在C++中输入正确的电子邮件地址格式
- 输入有效的输入值后仍有提示
- 当提示输入整数值时输入字符时,为什么程序会中断
- 提示输入CreateFile的凭据
- >使用 RegCreateKeyEx() 的 Windows 可执行文件不会提示输入 UAC 管理员权限并失败?
- 防止提示输入 PEM 密码
- 如何在不提示输入密码的情况下设置计划任务
- 如何使用循环显示菜单并重新提示输入
- c++ shell命令提示输入密码
- 如何同时(!CIN >> x)) 用于重新提示输入