C++ - 命令行参数

本篇博客主要介绍一个 c++ 命令行参数工具

简介

安装

  • 安装教程
  • 其实只需要导入 args.hxx 文件即可
  • 当作依赖放到 dep 目录中,在项目中使用,具体如何导入请看这儿

使用

  • 使用教程
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    #include<iostream>
    #include<args/args.hxx>

    int main(int argc, char** argv)
    {
    args::ArgumentParser parser("This is a test program.", "This goes after the options.");

    args::HelpFlag help(parser, "help", "Display this help menu", { 'h', "help" });
    args::ValueFlag<bool> bar(parser, "flag", "flag", { 'b' });
    args::ValueFlag<int> integer(parser, "port", "The http port", { 'i' });
    args::ValueFlagList<char> characters(parser, "char list", "The character flag", { 'c' });
    args::Positional<std::string> foo(parser, "string", "The foo position", { 'h' });
    args::PositionalList<double> numbers(parser, "numbers", "The numbers position list", { 'd' });

    // start parse argument list
    try
    {
    parser.ParseCLI(argc, argv);
    }
    catch (args::Help & help)
    {
    std::cout << parser << ", error = " << help.what() << std::endl;
    return false;
    }
    catch (args::ParseError & e)
    {
    std::cout << parser << ", error = " << e.what() << std::endl;
    return false;
    }
    catch (args::ValidationError & e)
    {
    std::cout << parser << ", error = " << e.what() << std::endl;
    return false;
    }

    if (bar) { std::cout << "bar" << std::endl; }
    if (integer) { std::cout << "i: " << args::get(integer) << std::endl; }
    if (characters) { for (const auto ch : args::get(characters)) { std::cout << "c: " << ch << std::endl; } }
    if (foo) { std::cout << "f: " << args::get(foo) << std::endl; }
    if (numbers) { for (const auto nm : args::get(numbers)) { std::cout << "n: " << nm << std::endl; } }

    return 0;
    }