首页 > 解决方案 > 单位换算菜单

问题描述

我需要创建一个具有 5 个转换选项(“主菜单”)的转换程序。每个选择必须至少有 10 次转换。我已经编写了“主菜单”,但我正在为转换选项而苦苦挣扎。我不知道如何将它与主菜单连接起来。这是我的代码,如果可能,请帮我编辑它。(对不起,我的英语不好)。

#include <iostream>
#include<conio.h>
using namespace std;

int main()
{
    double mm, cm, m, km, in, ft, yd, mi;
    long double mm1, cm1, m1, km1, in1, ft1, yd1, mi1;
    char choice, mainmenu;
    int b, c;
    loop:
    {
mainmenu:
    {
    system("CLS");
    cout << "Available Conversions\n";
    cout << "1- Length\n";
    cout << "2- Volume\n";
    cout << "3- Temperature\n";
    cout << "4- Power\n";
    cout << "5- Length\n";
    cout << "6- Exit\n";
    cin >> choice;
    }
    
switch(choice)
   {
    case 1://Length
    cout << "a. kilometer to mile\n";
    cout << "b. mile to kilometer\n";
    cout << "c. feet to inches\n";
    cout << "d. inches to feet\n";
    cout << "e. yard to meter\n";
    cout << "f. meter to yard\n";
    cout << "g. mile to feet\n";
    cout << "h. feet to mile\n";
    cout << "i. meter to inches\n";
    cout << "j. inches to meter\n";
    cout << "k. Back to Main menu\n";
   }
    }
    
}

标签: c++

解决方案


创建一个带有验证循环的函数和一个switch带有case每个菜单项的语句。为每个菜单项创建一个函数并在项目的 中调用它case,然后return从函数中调用它。如果菜单项的工作是另一个菜单,请再次执行相同的操作:验证循环switch,更多函数调用。

这使所有功能都保持小、易于理解和易于测试。当您对 C++ 有更多经验时,您会找到更好的方法(例如将输入标记链接到要调用的函数的数据结构),因此您可以重用菜单循环,但现在保持简单。

示例菜单:

void main_menu()
{
    while (true) // loop forever. The return statements later will exit the function 
                 // and the loop when a good input is processed.
    {
        int option; // use appropriate input data type
        std::cout << "Please provide input: ";
        // more detailed menu option description goes here if you want one.
        if (std::cin >> option) // Always test user input.
                                // The users that aren't morons are trying to hack your 
                                // program. Never trust a user.
        {
            switch(option)
            {
                case 1:
                    do_main_menu_option_1(); // Call a function that does whatever 
                                             // option 1 is supposed to do
                    return; // leave function and loop.
                case 2:
                    do_main_menu_option_2();
                    return; 
                case 3:
                    do_main_menu_option_3();
                    return; 
                default:
                    std::cout << "Invalid input. Please try again." << std::endl;
            }
        }
        else
        {
            std::cout << "Invalid input. Please input a number." << std::endl;
            std::cin.clear(); // clear input error flag
            std::cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
                              // discard garbage input.
        }
    }
}

推荐阅读