0

我有以下代码,并试图弄清楚如何选择通过按任意键返回主菜单,只要未选择退出选项。我假设这个 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;
       }

    }
}
4

1 回答 1

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(true) 之前) 2.将 while(true) 更改为 while(cond)
3.在 else if (userinp == 'q' 之后添加这个 else 块) 堵塞

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


       }
于 2013-10-01T22:47:39.117 回答