I want to read two parameters from the command line: a string and a number. The number should be a positive integer smaller than 100.
int main (int argc, char *argv[])
{
char * string;
long int number;
/* are there really 2 parameters? */
if (argc != 3) exit(EXIT_FAILURE);
/* catch them */
string = argv[1];
number = atoi(argv[2]);
/* use them */
printf("String parameter: %s\n",string);
printf("Number parameter+1: %d\n",number+1);
}
The number of parameters (as int) and the parameters itself (as char*) are passed to "main".
Everybody writes main as int main (int argc, char *argv), I guess it's possible to use more descriptive names to the arguments of main, like int main (int argument_counter, char *arguments) but it's probably out of fashion - if you write C you should look serious after all.
The classical beginner's note: It must be considered that argv[0] is the program name (what is useful for example for syntax error messages), so the counter is always actually one more than you intuitively expected and you find the first real parameter as argv[1].
Parameter type: as the parameters are actually always strings, you must convert them using some conversion functions like atoi or strtol (I guess).
No comments:
Post a Comment