I have made little program for computing pi (π) as an integral. Now I am facing a question how to extend it to compute an integral, which will be given as an extra parameter when starting an application. How do I deal with such a parameter in a program?
Share
When you write your main function, you typically see one of two definitions:
int main(void)int main(int argc, char **argv)The second form will allow you to access the command line arguments passed to the program, and the number of arguments specified (arguments are separated by spaces).
The arguments to
mainare:int argc– the number of arguments passed into your program when it was run. It is at least1.char **argv– this is a pointer-to-char *. It can alternatively be this:char *argv[], which means ‘array ofchar *‘. This is an array of C-style-string pointers.Basic Example
For example, you could do this to print out the arguments passed to your C program:
I’m using GCC 4.5 to compile a file I called
args.c. It’ll compile and build a defaulta.outexecutable.Now run it…
So you can see that in
argv,argv[0]is the name of the program you ran (this is not standards-defined behavior, but is common. Your arguments start atargv[1]and beyond.So basically, if you wanted a single parameter, you could say…
./myprogram integralA Simple Case for You
And you could check if
argv[1]wasintegral, maybe likestrcmp("integral", argv[1]) == 0.So in your code…
Better command line parsing
Of course, this was all very rudimentary, and as your program gets more complex, you’ll likely want more advanced command line handling. For that, you could use a library like GNU
getopt.