2012-01-14 111 views
0

我想要一个接受用户输入的菜单显示。但是,我希望用户能够返回到菜单的开头以重新选择选项。如何使用循环显示菜单并重新提示输入?

while(end != 1) { 
    display menu options 
    prompt user for input 
     if(input == x) { 
      do this 
     } 
     else 
      do that 
} 

然后,我希望它跳回到循环的开始并再次提出问题。我如何做到这一点,而不是在整个屏幕上创建无限循环的菜单打印?

回答

1

不幸的是,你并没有真正表现出你正在使用的代码,而是一些伪代码。因此,很难说出你实际想要做什么。然而,从我的问题和伪码的描述来看,我怀疑问题的根源在于你不检查输入,也不会将数据流恢复到合理的状态!要阅读菜单选项,您可能想要使用类似于此的代码:

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::getline()std::string;你也行只是std::istream::ignore()其余

可能还有其他的问题,你的菜单,但没有看到具体的代码,我觉得这是很难说的具体问题是什么。

0

而不是使用的同时,可以考虑使用功能,这样你就可以把它在你需要它:

void f() 
{ 
    if(end != 1) { 
     display menu options 
     prompt user for input 
      if(input == x) { 
       do this 
       f(); 
      } 
      else{ 
       do that 
       f(); 
      } 
    } 
} 
0

我不知道你找什么或者但这是一个菜单的一些粗糙的代码

while(1){ 
cout<<"******* Menu  ********\n"; 
cout<<"--  Selections Below  --\n\n"; 
cout<<"1) Choice 1\n"; 
cout<<"2) Choice 2\n"; 
cout<<"3) Choice 3\n"; 
cout<<"4) Choice 4\n"; 
cout<<"5) Exit\n"; 
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; 
     }