Print a Simple Menu C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#include <iostream> using namespace std; int main() { int choice; // Display the menu cout << "Simple Menu:" << endl; cout << "1. Start New Game" << endl; cout << "2. Load Game" << endl; cout << "3. Options" << endl; cout << "4. Exit" << endl; // Input user's choice cout << "Enter your choice (1-4): "; cin >> choice; // Perform action based on user's choice using a switch statement switch (choice) { case 1: cout << "Starting a new game..." << endl; break; case 2: cout << "Loading game..." << endl; break; case 3: cout << "Opening options..." << endl; break; case 4: cout << "Exiting the program. Goodbye!" << endl; break; default:
cout << "Invalid choice! Please enter a number between 1 and 4." << endl; break; } return 0; } |
Explanation:
- Menu Display:
- The program first displays a simple menu with four options:
- Start New Game
- Load Game
- Options
- Exit
- The program first displays a simple menu with four options:
- User Input:
- The program prompts the user to enter a choice (a number between 1 and 4).
- Switch Statement:
- The
switch
statement evaluates the user’s choice:case 1
: Prints “Starting a new game…”case 2
: Prints “Loading game…”case 3
: Prints “Opening options…”case 4
: Prints “Exiting the program. Goodbye!”default
: Handles any invalid choice (not between 1 and 4) by displaying an error message.
- The
- Output:
- Depending on the user’s choice, the program prints a corresponding message.
Example Outputs:
Example 1: Valid Choice
Input:
- Choice:
1
Output:
1 2 3 4 5 6 7 |
Simple Menu: 1. Start New Game 2. Load Game 3. Options 4. Exit Enter your choice (1-4): 1 Starting a new game... |
Example 2: Valid Choice
Input:
- Choice:
4
Output:
1 2 3 4 5 6 7 |
Simple Menu: 1. Start New Game 2. Load Game 3. Options 4. Exit Enter your choice (1-4): 4 Exiting the program. Goodbye! |
Example 3: Invalid Choice
Input:
- Choice:
5
Output:
1 2 3 4 5 6 7 |
Simple Menu: 1. Start New Game 2. Load Game 3. Options 4. Exit Enter your choice (1-4): 5 Invalid choice! Please enter a number between 1 and 4. |