Evgenii Legotckoi
Evgenii LegotckoiNov. 18, 2018, 5:57 a.m.

Boost - Console program menu using boost::program_options

And here is an article on the boost of my some accumulated materials. I offer you the option of writing a console program with support for the console menu, which is implemented using boost::program_options .

boost::program_options is responsible for processing the arguments passed to the program and sets all the necessary variables without the need to implement long logic from if else branches. This is already implemented inside boost::program_optons .

Suppose our program takes the following data as arguments

  • input file path
  • output file path
  • the size of the block being processed, no matter why, we will not do anything with it, just have such a parameter in the program.

Also, the program will have a help menu, which will be the console menu.

The figure below shows the use of this program.


Project structure

This program will be written using the CMake build system, without using the Qt library . This will be a tutorial purely for boost.

Посмотрим на структуру проекта.

В данном проекте есть

  • CMakeLists.txt -  CMake configuration file
  • main.cpp - file with main function
  • EApplication.h - header file of the main class of the application
  • EApplication.cpp - source file of the main application class

We write a project using OOP.

CMakeLists.txt

To begin with, let's deal with the configuration of the project, since this project is written using the boost library, it needs to be configured to work.

I note that this project was created under the Linux operating system, so there may be differences in the settings under the Windows or Mac OS.

Also, if you do not have the Boost development kit, then for example under Ubuntu you can do it like this

sudo apt-get install libboost-all-dev

Look at the project setup

cmake_minimum_required(VERSION 3.12)
project(Menu)

set(CMAKE_CXX_STANDARD 17)

find_package(Boost 1.58.0 COMPONENTS filesystem program_options)

set(SOURCE_FILES
        main.cpp
        EApplication.cpp
        EApplication.h)

if(Boost_FOUND)
    include_directories(${Boost_INCLUDE_DIRS})
    add_executable(Menu ${SOURCE_FILES})
    target_link_libraries(Menu ${Boost_LIBRARIES})
endif()

As you can see, I connected the standard C ++ 17. In this case, it does not matter, you can build the project and the standards C + + 11 or C + + 14.

This is the minimum required version of CMake. This version was installed on my PC.

Then we look for the boost components we need.

  • filesystem - we will save information about the file
  • program_options - to form a console menu

The if enfif condition specifies the libraries, their header files, and the source files of the project.

main.cpp

Let's look at the contents of the file with the main function. An application instance will be created there and its exec () method will be executed to run the main program logic.Let's look at the contents of the file with the main function. An application instance will be created there and its exec () method will be executed to run the main program logic..

#include <iostream>

#include "EApplication.h"

int main(int argc, const char* argv[])
{
    EApplication app(argc, argv);
    return app.exec();
}

EApplication.h

And now the most interesting, the program itself with the console menu.

#ifndef MENU_EAPPLICATION_H
#define MENU_EAPPLICATION_H

#include <boost/program_options.hpp>
#include <boost/filesystem/fstream.hpp>

namespace po = boost::program_options;
namespace fs = boost::filesystem;

class EApplication
{
public:
    explicit EApplication(int argc, const char** argv);

    int exec();

private:
    // And now the most interesting, the program itself with the console menu.
    po::options_description m_desc {"Allowed options"};
    po::variables_map m_vm; // container for saving selected program options

    // Required variables for working with menu options
    size_t m_blockSize;
    fs::path m_inputFilePath;
    fs::path m_outputFilePath;
};


#endif //MENU_EAPPLICATION_H

EApplication.cpp

#include "EApplication.h"

#include <iostream>

EApplication::EApplication(int argc, const char **argv)
{
    // Add menu items
    m_desc.add_options()
            ("help", "produce help message")  // Help
            ("input-file,i",  po::value<fs::path>(&m_inputFilePath)->composing(), "set input file path")              // Input file, you can write either --input-file, or -i
            ("output-file,o", po::value<fs::path>(&m_outputFilePath)->composing(), "set output file path")            // Output file
            ("block-size,b",  po::value<size_t>(&m_blockSize)->default_value(1024 * 1024), "set block size in bytes") // Block size
            ;
    po::store(po::parse_command_line(argc, argv, m_desc), m_vm);  // parse passed arguments
    po::notify(m_vm); // write arguments to variables in the program
}

int EApplication::exec()
{
    // If there is a request for help
    if (m_vm.count("help"))
    {
        // Then we display the menu description
        std::cout << m_desc << std::endl;
        return 1;
    }

    // If at least input and output parameters were entered
    if (m_vm.count("input-file") && m_vm.count("output-file"))
    {
        // then we initialize the program, but in this case we only display information about the entered parameters
        std::cout << m_inputFilePath << '\t' << m_outputFilePath << '\t' << m_blockSize << std::endl;
    }
    else
    {
        // Otherwise, we offer to see the help.
        std::cout << "Please, use --help option for information" << std::endl;
        return 1;
    }

    // ToDo something
    // Here we can put program logic in a while() or for(;;) loop

    return 0;
}

Conclusion

This library boost::program_options is really very useful and allows you to get rid of a large number of problems when writing the console menu. At a minimum, it allows you to write a very compact program code, and also very quickly implement the menu in a console application.

Git Repository Link

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
ИМ
Игорь МаксимовNov. 22, 2024, 10:51 p.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiNov. 1, 2024, 12:37 a.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 6:19 p.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 5:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 9:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 25, 2024, 1:11 a.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 5:04 p.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 1:49 p.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 7:10 p.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks