C++ 如何生成打印菜单的函数?

C++ 如何生成打印菜单的函数?,c++,C++,我正在玩弄函数,我想知道是否可以制作一个菜单,但将它放在函数中,然后在主函数中调用该函数。例如: cout << "Enter 1 for info" << endl; cout << " " << endl; cout << "Enter 2 to Start" << endl; cout << " " << endl; cout << "Enter 3

我正在玩弄函数,我想知道是否可以制作一个菜单,但将它放在函数中,然后在主函数中调用该函数。例如:

cout << "Enter 1 for info" << endl; 
    cout << " " << endl;
    cout << "Enter 2 to Start" << endl;
    cout << " " << endl;
    cout << "Enter 3 to Quit" << endl;

    cin >> menu;

cout以下是一个简单的示例:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int MenuSelect() {
    cout << endl;
    cout << "Enter 1 for info" << endl;
    cout << " " << endl;
    cout << "Enter 2 to Start" << endl;
    cout << " " << endl;
    cout << "Enter 3 to Quit" << endl;

    int selected = 0;
    string input;
    cin >> input;
    if (stringstream(input) >> selected) {
        return selected;
    }
    else {
        return -1;
    }
}

void start() {

}

int main() {
    int selected = -1;
    while ((selected = MenuSelect()) != 3) {
        if (selected < 1) {
            cout << "Invalid option" << endl;
        }
        else if (selected == 1) {
            cout << "Info" << endl;
        }
        else if (selected == 2) {
            cout << "START!" << endl;
            start();
        }
        else {
            cout << "Invalid option" << endl;
        }
    }

    return 0;
}
#包括
#包括
#包括
使用名称空间std;
int MenuSelect(){

通常情况下,表格“是否可以做X”中的所有问题都可以用简单的“是”来回答是的,你可以把你所显示的代码放在一个不同于代码>主< /代码>的函数中。试试FSM。当然可以做这样的事情。C++中一切都是可能的。你知道如何写和调用函数吗?注意你的例子中没有函数,所以不清楚你实际上帮助你显示C。ode可以实现您所描述的功能,只是不在函数内部,然后我们可以帮助您重构它。