2013-10-01 94 views
0

我有以下代碼,並試圖找出如何通過點擊任意鍵返回到主菜單的選項,只要不選擇退出選項。我假設這個while循環是如何完成的,但是當我執行代碼時,它將在1次迭代後終止。我只是在學習C++,所以我不太清楚如何瀏覽這個問題。返回主菜單(嵌套列表,C++)

//Runs a program with a menu that the user can navigate through different options with via text input 

#include <iostream> 
#include <cctype> 
using namespace std; 

int main() 
{ 
    char userinp; 
    cout<<"Here is the menu:" << endl; 
    cout<<"Help(H)  addIntegers(A)  subDoubles(D)   Quit(Q)"; 

    cin >> userinp; 
    userinp = tolower(userinp); 
    int count = 1; 
    while (count == 1) 
    { 
     if (userinp == 'h') 
     { 
      cout <<"This is the help menu. Upon returning to the main menu, input A or a to add 2 intergers." << endl; 
      cout <<"Input D or d to subtract 2 doubles. Input Q or q to quit."; 
      count = 1; 
      return count; 
     } 

     else if (userinp == 'a') 
     { 
      int a, b, result; 
      cout <<"Enter two integers:"; 
      cin >> a >> b; 
      result = a + b; 
      cout << "The sum of " << a << " + " << b << " = " << result; 
      count = 1; 
     return count; 
     } 
     else if (userinp == 'd') 
     { 
      double a, b, result; 
      cout <<"Enter two integers:"; 
      cin >> a >> b; 
      result = a - b; 
      cout << "The difference of " << a << " - " << b << " = " << result; 
      count = 1; 
      return count; 
     } 
     else if (userinp == 'q') 
     { 
      exit(0); 
     } 
     else 
     { 
      cout <<"Please input a valid character to navigate the menu - input the letter h for the help menu"; 
      cout << "Press any key to continue"; 
      count = 1; 
      return count; 
     } 

    } 
} 
+0

所有代碼的流向'return',除了一個 - 這確實一個'exit'。但是''''在'main'中被調用時'return'和'exit'是一樣的。您可能想要跳到下一個循環迭代:「繼續」。 (編輯:如果你有很長的'if's列表,你甚至不需要那個。) – usr2564301

+0

有沒有一種方法可以在返回主菜單之前提示用戶敲一下鍵? – Sean

回答

0

除去

else 
     { 
      cout <<"Please input a valid character to navigate the menu - input the letter h for the help  menu"; 
      cout << "Press any key to continue"; 
      count = 1; 
      return count; 
     } 

代替而與(計數== 1)它更改爲同時(真)// q被按壓

also have this part inside while loop i.e 
    while(true) 
{ 
    cout<<"Here is the menu:" << endl; 
    cout<<"Help(H)  addIntegers(A)  subDoubles(D)   Quit(Q)"; 

    cin >> userinp; 
    userinp = tolower(userinp); 
} 

,直到這意味着汽車無環有一個提示繼續:
1.add bool cond = true;(before while(true)) 2.change while(true)to while(cond)
3.添加這個else塊否則,如果之後(userinp == 'Q')塊

else 
{   char ch; 
      cout << "Press y to continue"; 
      cin>>ch; 
      if(ch=='y') 
     { 
     cond =true; 
     } 
else 
{ 
cond =false; 
exit(0); 
} 


     } 
+0

我想要有一個選項來確保如果4個命令之一未執行,它會提示用戶他們需要輸入4個命令之一而不退出程序。 – Sean

+0

我改變了while循環是同時(真),它仍然在退出後,1迭代:( – Sean

+0

@Sean看到編輯現在 –