返回主菜单(嵌套列表,c ++)

时间:2013-10-01 22:42:36

标签: c++ loops menu nested

我有以下代码,并试图找出如何通过点击任何键返回主菜单的选项,只要没有选择退出选项。我假设有一些东西,而while循环是如何完成的,但是当我执行代码时它会在1次迭代后终止。我只是在学习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;
       }

    }
}

1 个答案:

答案 0 :(得分: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;
       }

而不是while(count == 1)将其更改为while(true)//这意味着连续循环直到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;(while while(true)) 2.改变(真实)到while(cond)
3.如果(userinp =='q')阻止

,则在else之后添加其他阻止
else
 {          char ch;
            cout << "Press y to continue";
            cin>>ch;
            if(ch=='y')   
        {
         cond =true;
        }
else
{
cond =false;
exit(0);
}


       }