Get Parameters with C

From LPTMS Wiki
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Get parameters

  • interactive approach:

<source lang="c">

  1. include "stdio.h"

int main() {

 char * c;
 int i = 0;
 double d = 0.0;
 printf("Enter a word\n");
 scanf("%s",c);
 printf("Enter an integer\n");
 scanf("%d",&i);
 printf("Enter a double\n");
 scanf("%lf",&d);
 printf("You gave : %s %d %lf",c,i,d);
 printf("\n");
 return 0;

} </source>

  • from the command line:

<source lang="c">

  1. include "stdio.h"

int main(int argc, char* argv[]) {

 if(argc != 4)
   {
     printf("\tUsage:\t");
     printf("%s",argv[0]);
     printf(" <char> <integer> <double>\n");
   }
 else
   {
     char * c =  argv[1];
     int i = atoi(argv[2]);
     double d = atof(argv[3]);
     printf("You gave : %s %d %lf",c,i,d);
     printf("\n");
   }
 return 0;

} </source>

  • from a file, considering that you have a defined routine process() to do the job

<source lang="c">

  1. include "stdio.h"

void process(FILE * file) { ...fscanf(...)... }

int main(int argc, char* argv[]) {

 if(argc != 2)
   {
     printf("\tUsage:\t");
     printf("%s",argv[0]);
     printf(" <inputfile>\n");
   }
 else
   {
     char * filename =  argv[1];
     FILE * input = fopen(filename,'r');
     process(input);
     fclose(filename);
   }
 return 0;

} </source>