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

Join 86,383 C++ Programmers. There are 1,383 online right now! Ask your question and get quick answers from Dream.In.Code experts. Join the #1 programming help community on the internet! Registration is fast and FREE... Join Now!

Chat LIVE With a C++ Expert
Powered by LivePerson.com

Register to Make This Box Go Away!

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 - 10: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




Register to Make This Ad Go Away!

Amadeus
Group Icon



post 15 Jul, 2007 - 07: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

tralfas
*



post 9 Mar, 2008 - 08:53 PM
Post #3
wow that was very helpful i always wondered what those were for and now i know. thanks!


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

 

Lo-Fi Version Time is now: 5/17/08 03:53AM

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