Skip to content
Sign upLog in
← Back to Community
Easy Console Menu in C++
Profile icon
ANDREWVOSS

A header file with code for creating a console menu. The header contains 3 classes 1 of them is a struct but whatever

MenuItem

An item that can be added to a menu. Includes a name, a description, and an action to be run when the item is selected

Menu

The main class you'll be using. Includes a name and description like a MenuItem, as well as some methods.

AddMenu

Adds a submenu to the menu.

AddAction

Adds an item to the menu.

Init

Works all the magic, allowing the user to navigate the menu.

MainMenu

A derived class of Menu that adds an inline wrapper for the Init method.

Example Usage

#include <iostream> #include "ConsoleMenu.hpp" int main() { // Create our main menu MainMenu main("main", "main menu"); // Create a submenu to add to the main menu Menu sub("sub", "submenu"); // Add a submenu to the submenu sub.AddMenu({"sub", "submenu within a submenu"}); // Add an action to the first submenu sub.AddAction({"bar", "action within a submenu", []() { std::cout << "Bar" << std::endl; }}); // Add the first submenu to the main menu main.AddMenu(sub); // Add an action to the main menu main.AddAction({"foo", "some action", []() { std::cout << "Foo" << std::endl; }}); // Start the menu main.Init(); // Exit after the menu is done return 0; }
Voters
Profile icon
nloudev
Profile icon
DynamicSquid
Profile icon
ANDREWVOSS
Comments
hotnewtop
Profile icon
DynamicSquid

Nice! But try to use const references instead :)

AddMenu(Menu m) // bad AddMenu(Menu const& m) // good
Profile icon
ANDREWVOSS

@DynamicSquid
For inheritance, I assume?

Profile icon
DynamicSquid

@ANDREWVOSS
No, it's just when you pass by value, you are creating a copy, which is expensive. Passing by const-ref doesn't create unnecessary copies which can hinder performance. You can read more here: https://stackoverflow.com/questions/4986341/where-should-i-prefer-pass-by-reference-or-pass-by-value

Profile icon
ANDREWVOSS

@DynamicSquid
Oh, that makes a lot of sense.

Profile icon
CoderGautamYT

Cool :D

Profile icon
ANDREWVOSS
Profile icon
CoderGautamYT