atoi/atof
int main(int argc, char** argv){/* do stuff */}where
argc
, argument count, is the number of command-line
arguments (where the first argument is always the name of the
program), and argv
is the array of strings of the size
argc
that holds the command-line arguments (where the
first element, argv[0]
is the name of the program and
argv[1]
is the first actual argument).
When the program is run the operating system calls the main
function and provides its arguments as the array of blank-separated
strings taken from the command that ran the program.
You can convert the string representation of a double number into
the number using the function atof
, "ascii to double",
from stdlib.h
. For example,
int main(int argc, char** argv){ if(argc<2) fprintf(stderr,"%s: there were no arguments\n",argv[0]); else { for(int i=1;i<argc;i++){ double x = atof(argv[i]); printf("argument number %i = %g\n",i,x); } } return 0; }
getopt
./main -n 100 -e 0.001The program that interprets this command line might look like this,
#include"stdio.h" // " only to include in html, use < > #include"stdlib.h" #include"getopt.h" int main(int argc, char **argv) { double epsilon=0.1; int npoints=10; // default parameters while(1){ // reading options int opt = getopt(argc,argv,"n:e:"); // options n,e require argument if(opt == -1) break; // end of options switch(opt){ case 'n': npoints=atoi(optarg); break; // option "n" case 'e': epsilon=atof(optarg); break; // option "e" default: // something went wrong... fprintf(stderr, "Usage: %s [-n npoints] [-e epsilon]\n", argv[0]); exit(EXIT_FAILURE); } } printf("npoints=%i, epsilon=%g\n",npoints,epsilon); exit(EXIT_SUCCESS); }