2012-04-15 44 views
0

嘿,任何人都可以看到我的菜單在while循環中出現什麼問題,如果我在無限循環中按1,它會一直打印出dixie。我在菜單週圍有一段時間循環,以便菜單總是在那裏讓用戶返回選擇。 這裏是我的代碼:C++菜單。無限循環菜單

#include <iostream> 
using namespace std; 

int main() 
{ 
    int choice; 
    bool menu = true; 
    cout <<"========Welcome to the database menu========\n"; 

    cout << "Press 1 to insert a new record at a particular position\n" 
      "Press 2 to delete a record from a particular position\n" 
      "Press 3 to search the database and print results\n" 
      "Press 5 to find the average experience points of players at a particular level\n" 
      "Press 6 to find and remove all duplicate entries\n" 
      "Press 0 to quit\n\n\n\n\n\n\n\n\n"; 

    cout << "Choice: "; 
    cin >> choice; 
    //***************************************************************************** 
    // Switch menu to display the menu. 
    //***************************************************************************** 
    while(menu) 
    { 
     switch (choice) 
     { 
      case 1: 
       cout << "dixie"; 
       break; 
      case 2: 
       cout << "bexie"; 
       break; 
      default: 
       cout<< "That is not a choice!!!\n"; 
     } 
    }  
    getchar(); 
    getchar(); 
} 

回答

0

它說while (menu)這意味着它會繼續這樣做,直到你設置菜單false

此外,我想你想在循環中添加cin >> choice,或者它只是一次又一次地重複選擇。

+0

謝謝你得到它的建議。非常感謝。 – Pendo826 2012-04-15 13:06:06

2

沒有代碼,可以改變任何menuchoicewhile循環內。所以一旦它開始,它永遠不會停止。

+0

因此,如果我選擇了一個案件但仍然顯示菜單選項,我將如何阻止它從loopin? – Pendo826 2012-04-15 13:01:51

+0

問題是你的循環處於錯誤的地方。循環直到用戶選擇'0'爲止,但你必須在'switch'語句中處理'0'。查看我的答案,瞭解可能的解決方案,以便「while」循環應該去。 – 2012-04-15 13:03:59

0

我會想,while循環應該包括打印菜單選項,並讓用戶選擇像這樣一個選項:

while (menu) 
{ 
    cout <<"========Welcome to the database menu========\n"; 
    cout << "Press 1 to insert a new record at a particular position\n" 
      "Press 2 to delete a record from a particular position\n" 
      "Press 3 to search the database and print results\n" 
      "Press 5 to find the average experience points of players at a particular level\n" 
      "Press 6 to find and remove all duplicate entries\n" 
      "Press 0 to quit\n\n\n\n\n\n\n\n\n"; 

    cout<< "Choice: "; 
    cin>> choice; 

    switch (choice) 
    { 
     case 1: 
      cout << "dixie"; 
      break; 
     case 2: 
      cout << "bexie"; 
      break; 
     default: 
      cout<< "That is not a choice!!!\n"; 
    } 
} 

另一種可能性是剛剛cout << "Choice: "線之前啓動while循環。

0

menu變量總是在true的循環內。現在和while(true)一樣。