Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting
TIMEWEB

Boost - Console program menu using boost::program_options

cpp, Boost, Menu, C++

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

Comment

Comment

Only authorized users can write comments.
Sign in or Register, Please
Dec. 12, 2018, 6:49 p.m.
Yaroslav Chernetskyi

Qt - Test 001. Signals and slots

  • Result:31points,
  • Rating scores-10
Dec. 12, 2018, 6:19 a.m.
nikbobrecov

Qt - Test 001. Signals and slots

  • Result:57points,
  • Rating scores-2
Dec. 11, 2018, 6:59 p.m.
Feniks3000

C++ - Тест 003. Условия и циклы

  • Result:71points,
  • Rating scores1
Recent comments
Dec. 11, 2018, 9:01 p.m.
Евгений Легоцкой

Не знаю, какой-там конкретно эффект и если честно не хочется fl studio ради того, чтобы посмотреть устанавливать, но из того, что увидел в интернете. Предполагаю, что то, что вы хотите с...
Dec. 11, 2018, 7:25 p.m.
Vlad15007

Подскажите пожалуйста ( я новичок совсем)Можно ли организовать спрайт без этого окошка (как в fl studio fruity dance)?
Dec. 11, 2018, 3:06 p.m.
Евгений Легоцкой

Что интересно, если написать так from <application_name>.<module_name> import <filename> ,то PyCharm сносит крышу, если разрабатываешь в рамках проекта приложение, ко...
Dec. 11, 2018, 2:52 p.m.
Илья Чичак

Тут мне тоже есть что сказать=) Сами разрабы советуют импортировать следующим образом: from <application_name> import <module_name> Стоит избегать from . import &l...;
Dec. 11, 2018, 2:28 p.m.
Евгений Легоцкой

Твоя правда. Согласен. Свои миграции храню в репозитории. На продакшене только выполняю обновление структуры базы данных, после тестирования на дев сервере конечно (читай локальная машина разр...
Now discuss on the forum
Dec. 12, 2018, 5:52 p.m.
Михаиллл

Оказывается оно все переводит в нижний регистр и нужно так писать: SearchTableModel->setTable("\"Test2\"");
Dec. 12, 2018, 4:32 p.m.
Булат Гиниятов

Допустим в MyObject *myobject = new MyObject; есть метод start(){while(aaa){////////////////}} Как мне обратиться к методу stop(){aaa=false;} ? Соответственно по...
Dec. 12, 2018, 4:28 p.m.
xintrea

Как выяснилось в этом обсуждении: Отправка Email из Android в Qt для отправки Email в Android необходимо делать Java-метод, который и будет отправлять email. И этот Java-мет...
Dec. 12, 2018, 3:35 p.m.
lynx

если кому будет вдруг нужно, подумал я над предложением Евгения Но думаю, что проще какой-то функционал дополнить для TableView из Qt Quick Controls 2. вообще берем стандарт...
Dec. 12, 2018, 1:49 p.m.
Евгений Легоцкой

но у меня нет времени учиться ВЕЧНО давайте без истерик, вы это говорите человеку, который всю жизнь учился, учится и будет учиться, и в программировании всегда так, или учишься и...
Join us in social networks

For registered users on the site there is a minimum amount of advertising