bhylu.com

Advertisements

C++ Command-line Arguments

Require one count argument and return a useful exit status for invalid invocations.

How it works

main can receive argc and argv from the hosted runtime. Check argc before reading an argument position. Each argument remains text and needs complete conversion plus domain validation. This utility accepts one count from one through one hundred and writes usage or validation errors to stderr. Shell quoting happens before C++ receives the strings and varies by shell. Passing an argument into a numeric parser does not require constructing another shell command.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror command-line.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe 3 in PowerShell. On Unix-like systems run ./lesson 3. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · command-line.cpp

#include <iostream>
#include <charconv>
#include <string_view>
#include <system_error>

int main(int argc, char *argv[]) {
    if (argc != 2) { std::cerr << "Usage: lesson COUNT\n"; return 2; }
    std::string_view text{argv[1]};
    int count{};
    auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), count);
    if (error != std::errc{} || end != text.data() + text.size() || count < 1 || count > 100) {
        std::cerr << "COUNT must be 1..100\n"; return 2;
    }
    std::cout << "Requested: " << count << '\n';
}

Expected result

Requested: 3

Run the executable with argument 3. The range check protects the operation’s business limit after conversion succeeds. An empty argument has a valid terminated argv buffer and is rejected by from_chars. Nonzero status lets a caller detect failure without inspecting the normal result text. These fixtures exercise actual executable invocations in the review.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.