Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 132,415 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,431 people online right now. Registration is fast and FREE... Join Now!




Passing arguments to your program

 
Reply to this topicStart new topic

> Passing arguments to your program, How to use & impliment int argc char argv functionality

no2pencil
Group Icon



post 13 Jul, 2007 - 09:51 AM
Post #1


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


Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

Amadeus
Group Icon



post 15 Jul, 2007 - 06:21 AM
Post #2
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
Go to the top of the page
+Quote Post

tralfas
*



post 9 Mar, 2008 - 07:53 PM
Post #3
wow that was very helpful i always wondered what those were for and now i know. thanks!
Go to the top of the page
+Quote Post


Reply to this topicStart new topic
2 User(s) are reading this topic (2 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 11/22/08 09:10AM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month