2012-04-15 43 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)一样。