Site icon T4Tutorials.com

Print a Simple Menu C++

#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:

  1. Menu Display:
    • The program first displays a simple menu with four options:
      1. Start New Game
      2. Load Game
      3. Options
      4. Exit
  2. User Input:
    • The program prompts the user to enter a choice (a number between 1 and 4).
  3. 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.
  4. Output:
    • Depending on the user’s choice, the program prints a corresponding message.

Example Outputs:

Example 1: Valid Choice

Input:

Output:

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:

Output:

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:

Output:

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.

 

Exit mobile version