Skip to content

Cli_parser

Pierre Marguerie edited this page Dec 6, 2025 · 2 revisions

A lightweight C++ library designed to simplify the parsing of command-line arguments (argc/argv). It allows you to easily check for flags and retrieve their associated values.

Features

  • Flag Detection: Check if a specific flag (e.g., --help, -v) exists.

  • Value Retrieval: Extract values associated with flags (e.g., retrieving 8080 from -p 8080).

Integration

Include the header in your C++ file:

#include "cli_parser.hpp"

Note

This library requires argv to be cast as const. Please ensure your main function signature or your variable passing adheres to this.

API reference

Initialization

Initialize the parser by passing the standard arguments from main.

cli_parser::Parser parser(argc, argv);
Method Returns Description
hasFlag(string flag) bool Returns true if the flag exists in the arguments, false otherwise.
getValue(string flag) string Returns the value immediately following the specified flag. Empty string if it doesn't exist or is empty.

Usage example

Below is a complete example with Host and Port from the command line.

#include <iostream>
#include "cli_parser.hpp"

int main(const int argc, const char* argv[]) 
{
    // 1. Initialize the parser
    cli_parser::Parser p(argc, argv);

    // 2. Check for help flag or insufficient arguments
    if (p.hasFlag("--help") || argc < 2) {
        std::cout << "Usage: " << argv[0] << " [options]" << std::endl
                  << "\t-h <host> : The IP address of the server" << std::endl
                  << "\t-p <port> : The port to listen to" << std::endl;
        return 0;
    }

    // 3. Parse specific values
    if (p.hasFlag("-h") && p.hasFlag("-p")) {
        std::string host = p.getValue("-h");
        std::string port = p.getValue("-p");

        std::cout << "Starting server on " << host << ":" << port << std::endl;
    } else {
        std::cerr << "Error: Missing -h or -p parameter." << std::endl;
        return 1;
    }

    return 0;
}

Output:

# Display help
./my_program --help

# Run with parameters
./my_program -h 127.0.0.1 -p 8080
# Output: Starting server on 127.0.0.1:8080

Clone this wiki locally