现有主菜单和子菜单,分别用switch函数进行操作的选择,子菜单中输入0就可以返回主菜单,具体实现的代码是什么
时间: 2024-03-23 18:39:10 浏览: 16
以下是一个示例代码,用于实现主菜单和子菜单的选择:
```c++
#include <iostream>
using namespace std;
int main() {
int choice = 0;
do {
cout << "Main Menu" << endl;
cout << "1. Option 1" << endl;
cout << "2. Option 2" << endl;
cout << "3. Option 3" << endl;
cout << "0. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "You selected Option 1" << endl;
break;
case 2:
cout << "You selected Option 2" << endl;
break;
case 3:
cout << "You selected Option 3" << endl;
break;
case 0:
cout << "Exiting..." << endl;
break;
default:
cout << "Invalid choice. Please try again." << endl;
break;
}
if (choice == 0) {
break;
}
int subChoice = 0;
do {
cout << "Sub Menu" << endl;
cout << "1. Sub Option 1" << endl;
cout << "2. Sub Option 2" << endl;
cout << "3. Sub Option 3" << endl;
cout << "0. Back to Main Menu" << endl;
cout << "Enter your choice: ";
cin >> subChoice;
switch (subChoice) {
case 1:
cout << "You selected Sub Option 1" << endl;
break;
case 2:
cout << "You selected Sub Option 2" << endl;
break;
case 3:
cout << "You selected Sub Option 3" << endl;
break;
case 0:
cout << "Returning to Main Menu..." << endl;
break;
default:
cout << "Invalid choice. Please try again." << endl;
break;
}
} while (subChoice != 0);
} while (choice != 0);
return 0;
}
```
在这个示例代码中,我们使用了两个嵌套的 do-while 循环,一个用于主菜单的选择,另一个用于子菜单的选择。在每个循环中,我们使用 switch 语句来根据用户的选择执行相应的操作。当用户在子菜单中输入 0 时,我们会跳出子菜单循环,返回到主菜单循环。当用户在主菜单中输入 0 时,我们会跳出主菜单循环,结束程序的执行。