Full Version: Passing arguments to your program
Dream.In.Code > Programming Tutorials > C++ Tutorials
no2pencil
int main(int argc, char *argv[])
** How to use & impliment int argc char argv functionality aka passing arguments to your program **

In order to allow your program to accept arguments, you need to declair 2 items in your main function. Those being integer argc & the charactor argv array. These two items accept the arguments, & allow you to use them inside of your program. This will both be explained in detail, as well examples will be given.

Argc is the integer value of how many arguments have been passed. It is important to remember that the default value will be the command itself. So for example, if 3 arguments are passed, then argv[1] will be the command, giving argc a value of 4 (0 through 4). If your program absolutly must recieve a specific number of arguments, you can use this value to break execution, & then prompt the user on the usage of your program.

Argv is the other value being passed, & it is a charactor array. You can use argv[] to referance each array, or argv[][] to referance each charactor of each array, or a 2d array.

Code example:
CODE

#include <stdio.h>

// main program
int main(int argc,char *argv[]) {
    int i=1;
    // decode arguments
    if(argc < 2) {
        printf("You must provide at least one argument\n");
        exit(0);
    }
    // report settings
    for (;i<argc;i++) printf("Argument %d:%s\n",i,argv[i]);
    return(0);
}



Usage examples:
CODE

server:/home/user/code>./prog
You must provide at least one argument


CODE

server:/home/user/code>./prog help me out
Argument 1:help
Argument 2:me
Argument 3:out


Amadeus
For clarity's sake, the argv, or argument vector, parameter is actually a pointer to an array of string pointers.

Alternate:

http://publications.gbdirect.co.uk/c_book/...ts_to_main.html
tralfas
wow that was very helpful i always wondered what those were for and now i know. thanks!
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2008 Invision Power Services, Inc.