Reading command line arguments

Reading command line arguments

How to:

In C++, command-line arguments are received in main() as an array of character pointers. Here’s how you grab them:

#include <iostream>
int main(int argc, char* argv[]) {
    std::cout << "You've entered " << argc << " arguments:\n";
    for (int i = 0; i < argc; ++i) {
        std::cout << argv[i] << "\n";
    return 0;

Sample Output: (Assuming executed as ./myProgram foo bar)

You've entered 3 arguments:

Deep Dive

Way back when, command line was the only way to interact with programs. Today’s GUIs are grand, but command line persists, especially in server or development environments. It offers speedy, scriptable control.

Alternatives to built-in argv and argc include libraries like Boost.Program_options for fancier parsing. There’s also the getopt() function in Unix-like systems for more traditional command line fans.

Implementing argument parsing from scratch lets you tailor it, but watch for security holes. Don’t trust user input blindly—always validate and sanitize.

See Also