Get Parameters with C: Difference between revisions
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...") |
mNo edit summary |
||
| Line 3: | Line 3: | ||
* interactive approach: | * interactive approach: | ||
<source lang=" | <source lang="c"> | ||
#include "stdio.h" | #include "stdio.h" | ||
| Line 26: | Line 26: | ||
* from the command line: | * from the command line: | ||
<source lang=" | <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=" | <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); | |||
} | |||
return 0; | |||
} | |||
</source> | </source> | ||
Revision as of 21:25, 12 November 2012
Get parameters
- interactive approach:
<source lang="c">
- 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">
- 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">
- 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);
}
return 0;
} </source>