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

本文介绍了Python的argparse库和C++的cxxopts库,它们都用于解析命令行参数,argparse基于C++17,而cxxopts支持GNU风格选项。分别提供了使用示例和链接供进一步学习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老狼IT工作室

你的鼓励将是我创作的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值