[C++] Introduction and use of third-party command line parsing libraries argparse and cxxopts

Introduction to argparse library

The name is the same as Python's command line parameter parsing library, and the usage is similar.

Github:https://github.com/p-ranav/argparse

argparse is a header-only command line parameter parsing library based on C++17 and relies on C++17 related features.

argparse use cases

#include <argparse/argparse.hpp>

int main(int argc, char *argv[]) {
  argparse::ArgumentParser program("program_name");

  program.add_argument("square")
    .help("display the square of a given integer")
    .scan<'i', int>();

  try {
    program.parse_args(argc, argv);
  }
  catch (const std::exception& err) {
    std::cerr << err.what() << std::endl;
    std::cerr << program;
    return 1;
  }

  auto input = program.get<int>("square");
  std::cout << (input * input) << std::endl;

  return 0;
}

For more usage, you can read  https://github.com/p-ranav/argparse/ 

cxxopts library introduction

Github:GitHub - jarro2783/cxxopts: Lightweight C++ command line option parser

This is a lightweight C++ option parser library, supporting the standard GNU style syntax for options.

cxxopts is a header-only command line parameter parsing tool, and its value depends on the relevant features of C++11.

cxxopts use case

#include <cxxopts.hpp>


int main(int argc, char** argv)
{
    cxxopts::Options options("test", "A brief description");

    options.add_options()
        ("b,bar", "Param bar", cxxopts::value<std::string>())
        ("d,debug", "Enable debugging", cxxopts::value<bool>()->default_value("false"))
        ("f,foo", "Param foo", cxxopts::value<std::string>()->implicit_value("implicit")        
        ("h,help", "Print usage")
    ;

    auto result = options.parse(argc, argv);

    if (result.count("help"))
    {
      std::cout << options.help() << std::endl;
      exit(0);
    }
    bool debug = result["debug"].as<bool>();
    std::string bar;
    if (result.count("bar"))
      bar = result["bar"].as<std::string>();
    int foo = result["foo"].as<int>();

    return 0;
}

For more usage, you can read  GitHub - jarro2783/cxxopts: Lightweight C++ command line option parser

Guess you like

Origin blog.csdn.net/u011775793/article/details/135309235