Get Parameters with C

From LPTMS Wiki
(Redirected from Basic start with C)
Jump to: navigation, search

Get parameters

  • interactive approach:

#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;
}
  • from the command line:

#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;
}
  • from a file, considering that you have a defined routine process() to do the job

#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;
}