Computer Science Canada

command line arguments

Author:  Geminias [ Fri Jan 06, 2006 10:45 pm ]
Post subject:  command line arguments

hi friends,

how would i be able to accept command line arguments for a program?

So if i had a program called: ROT13 and i wanted to decrypt a certain code i could just type: ROT13 -<certain code> and it would decrypt it for me and display it on screen.

Author:  wtd [ Fri Jan 06, 2006 11:11 pm ]
Post subject:  Re: command line arguments

What do you think the arguments to "main" are for?

code:
int main(int argc, char ** argv)

Author:  Geminias [ Sat Jan 07, 2006 12:11 am ]
Post subject: 

for anyone else whose interested in knowing:

code:
int main(int argc, char * argv[])


"argc" is automatically determined by how many spaces you use.
argv is a pointer to character array.


so if you typed: "myprog.exe argument1 argument2"
argc = 2, because there were two spaces.
argv[0] = name of program "myprog.exe"
argv[1] = argument1
argv[2] = argument2


big thanks to wtd for his guidance. Also:

Quote:
int main(int argc, char ** argv)


does the "**" mean "const char * argv"?[/quote]

Author:  wtd [ Sat Jan 07, 2006 12:27 am ]
Post subject: 

No, ** mean pointer to pointer. A C-style (as opposed to C++ style) string is an array of characters terminated by the null character. An array in C and C++ is just a glorified pointer. Thus an array of C-style string is an array or arrays of characters.

Or... a pointer to a pointer to a character.

Author:  wtd [ Sat Jan 07, 2006 12:29 am ]
Post subject: 

Also, if you provide two arguments to a program, argc is 3, since there are three strings in the array.

Author:  Geminias [ Sat Jan 07, 2006 12:31 am ]
Post subject: 

c++:


int main (int argc, char ** argv)
{
     std::cout << * argv;

     return 0;
}



all i seem to be able to get is an address when i use a glorified pointer.

Author:  wtd [ Sat Jan 07, 2006 1:34 am ]
Post subject: 

When I compile and run that (after adding the include for iostream), I get:

code:
C:\>g++ args.cpp

C:\>a
a

Author:  Geminias [ Sat Jan 07, 2006 3:09 am ]
Post subject: 

ok for some reason i'm getting it now. wierd, before it was only giving me an address.


: