C/C++ >> i need help with command line arguments in c++
Posted by hex on 05:49:00 04-11-2003
i know how to use argc and argv[] to check the nmber of commands and print them to the screen but i want to copy the string of characters in argv[] to an array. ive tried to do it several ways with strcpy(), but every thing ive tried woulnt work. any one know how to do this?
Posted by Yjo on 05:51:00 04-12-2003
Code:
main( int argc, char *argv[ ]}
{
...

argv == argument list
argc == num of elements in arg list
-->=1 as the name of the task as invoked is always the 1'st element of the array.

you shouldnt really need to copy the args into an array of fixed-len chars for any application--most progs will only need to use strcmp() and atoi() on the pointers themselves in order to parse CLI invocation arguments; and, what's more, by leaving the strings where they are you can let the OS do all the worrying about allocating memory and not overwriting buffers etc.

e.g.:
Code:
char* interesting;
int num=10;//by default
bool ucaseT=false;
if(argc <= 1){
printf("useage: PROGNAME [-n number] [-t] [-T] somestring");
return -1;}
for(int i=1;i<argc-1;i++){
if(!strcmp(argv[i],"-T"))
ucaseT=true;
else if(!strcmp(argv[i],"-t"))
ucaseT=false;
else if(!strcmp(argv[i],"-n")&&++i<argc)
num=atoi(argv[i]);
}

interesting=argv[argc];
...


don't be surprised if that doesnt work, it's ... not meant to.

[ This Message was edited by: Yjo on 2003-04-12 05:52 ]