[C++] 第三方库命令行解析库argparse和cxxopts介绍和使用

发布时间:2024-01-03 17:26:17

argparse库介绍

名字和python的命令行参数解析库一样,用法也差不多。

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

argparse是基于C++17的header-ongly的命令行参数解析库,依赖于C++17相关特性。

argparse使用案例

#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;
}

更多用法,可以阅读?https://github.com/p-ranav/argparse/?

cxxopts库介绍

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是一个header-only的命令行参数解析工具,值依赖于C++ 11的相关特性。

cxxopts使用案例

#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;
}

更多用法,可以阅读?GitHub - jarro2783/cxxopts: Lightweight C++ command line option parser

文章来源:https://blog.csdn.net/u011775793/article/details/135309235
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。