←to practical programming

Note "command line"

atoi/atof

A small amount of numbers can be passed to a C-program via command-line arguments by declaring the main function as
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

One can also pass named command-line parameters (options) to their main-function. We shall only consider short, one-letter, options that are followed by a number, like this,
./main -n 100 -e 0.001
The 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);
}