菜单的嵌套循环(基本 c++)

Nested loops for menus (basic c++)

本文关键字:c++ 基本 嵌套循环 菜单      更新时间:2023-10-16

我遇到了错误,他们说a,q,h等不是声明的变量,但我不确定如何解决这个问题。这是我的代码示例。

我也收到一个错误,它无法识别 while 循环中的 userinp,但我不确定如何在不声明全局变量的情况下将变量存储从 while 循环外部转移到 while 循环内部,我想避免这种情况。

最后一个问题:我希望能够在每个菜单项之后立即将任何键返回到主菜单,但我不确定该使用什么。

任何帮助将不胜感激!

//Runs a program with a menu that the user can navigate through different options with via text input
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <ctype.h> 
#include <string>
using namespace std;
int main()
{
    int userinp;
    cout<<"Here is the menu:" << endl;
    cout<<"Help(H)      addIntegers(A)      subDoubles(D)           Quit(Q)";
    cin >> userinp;
    userinp = tolower(userinp);
    while userinp != q //loop while no q is input
    {
        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.";
        }
        if userinp == a
        {
            int a, b, result;
            cout <<"Enter two integers:";
            cin << a << b;
            result = a + b;
            cout << "The sum of " << a << " + " << b << " = " << result;
        }
    }
}

试试这个:

while(userinp != 'q') {

而这个:

if(userinp == 'h')

而这个:

if(userinp == 'a')

等等,您可能希望将userinp声明为char而不是int

如果要比较文字字符,则必须使用单引号。 如果要比较文本字符串,则需要双引号。 唯一不使用引号的比较文字数字。

您的输入也有错误。 您的>>应该是<<。将>>cin一起使用,将<<cout一起使用。

代码问题:你希望用户inp是一个字符,但你已经声明为整数2)如果条件应在括号内