views:

337

answers:

5

I'm currently trying to make a small application that performs different duties. Right now I have a console app pop up and ask what I want to do, but sometimes I would rather just launch it with something like MyApp.exe -printdocuments or some such thing.

Are there any tutorials out there that can show me a simple example of this?

+8  A: 

In C++, your main() function can have argc and argv parameters, which contain the arguments passed on the command line. The argc is the count of arguments (including the executable name itself), and argv is an array of pointers to null-terminated strings of length argc.

For example, this program prints its arguments:

#include <stdio.h>

int main(int argc, char *argv[])
{
    for (int i = 0; i < argc; i++) {
        printf("argv[%d]: %s\n", i, argv[i]);
    }
    return 0;
}

Any C or C++ tutorial will probably have more information on this.

Greg Hewgill
A: 

your entry point method i.e. in C++ your main method needs to look like

int main ( int argc, char *argv[] );

you can read this article and accomplish what you are trying to do

Perpetualcoder
+1  A: 

You would do well to use a library for this. Here are a few links that might get you started on command line arguments with c++.

  1. gperf
Vincent Ramdhanie
+5  A: 

You can use boost::program_options to do this, If you don't want to use boost library, you must parse main function arguments by yourself.

Lazin
+2  A: 

getopt is a posix function (implementations for windows exist) that can help you parse your arguments:

#include <unistd.h> // getopt

// call with my_tool [-n] [-t <value>]
int main(int argc, char *argv[])
{
    int opt;
    int nsecs;
    bool n_given = false, t_given = false;
    // a colon says the preceding option takes an argument
    while ((opt = ::getopt(argc, argv, "nt:")) != -1) {
        switch (opt) {
        case 'n':
            n_given = true;
            break;
        case 't':
            nsecs = boost::lexical_cast<int>(optarg);
            t_given = true;
            break;
        default: /* '?' */
            std::cerr << "Usage: "
                      << argv[0] << " [-t <value>] [-n]\n";
            return 1;
        }
    }
    return 0;
}
Johannes Schaub - litb