如何使用循环显示菜单并重新提示输入

How do I use a loop to display a menu and re-prompt for input?

本文关键字:提示 输入 新提示 循环 何使用 显示 菜单      更新时间:2023-10-16

我想要一个接受用户输入的菜单显示。但是,我希望用户能够回到菜单的开头重新选择选项。

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");
    }
}

这只是输入的大致布局。它可能会被封装到一个函数中(在这种情况下,您可能希望以某种不同的方式从闭合输入中解脱出来,可能使用异常或特殊的返回值)。他的主要部分是

  1. 使用std::isteam::clear()将流恢复到良好状态
  2. 跳过坏输入,在这种情况下使用具有std::stringstd::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;
        }