Get Parameters with C: Difference between revisions

From LPTMS Wiki
Jump to navigation Jump to search
(Created page with " == Get parameters == * interactive approach: <source lang="cpp"> #include "stdio.h" int main() { char * c; int i = 0; double d = 0.0; printf("Enter a word\n"); s...")
 
 
(2 intermediate revisions by the same user not shown)
Line 3: Line 3:


* interactive approach:
* interactive approach:
<source lang="cpp">
<source lang="c">
#include "stdio.h"
#include "stdio.h"


Line 26: Line 26:


* from the command line:
* from the command line:
<source lang="cpp">
<source lang="c">
#include "stdio.h"
#include "stdio.h"


Line 49: Line 49:
</source>
</source>


* from a file
* from a file, considering that you have a defined routine process() to do the job
<source lang="cpp">
<source lang="c">
#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>
</source>

Latest revision as of 16:04, 13 November 2012

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>