2012-01-14 39 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; 
     } 
相關問題