我在玩功能,我想知道是否可以制作菜单,但将其包含在功能中,然后在主菜单中调用该功能。一个例子是:
cout << "Enter 1 for info" << endl;
cout << " " << endl;
cout << "Enter 2 to Start" << endl;
cout << " " << endl;
cout << "Enter 3 to Quit" << endl;
cin >> menu;
我想要这个,但是在一个带有if和else语句的函数中,所以它将根据用户的选择打印出另一条语句。我正在使用c ++语言。
谢谢
这是一个入门的简单示例:
#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;
}