Next: File Handles
Up: Input/Output
Previous: Standard Input/Output/Error
Contents
Index
Command line arguments
Another method to get user inout is through the use
of command-line arguments when running a program:
my_program 34 66 dallas
where the arguments 34, 66, and dallas are
captured and subsequently used in your program. How this
can be done is illustrated in the following program:
#include <stdio.h>
int main(int argc, char *argv[]) {
int input;
if (argc != 2) {
printf("Usage: %s number\n", argv[0]);
exit(1);
}
input = atoi(argv[1]);
printf("You entered an integer %d.\n", input);
return 0;
}
Here,
- argc is an integer which will be set equal to
the number of arguments used (the name of the
program counts as one argument).
- argv is an array of strings containing the
command-line arguments used, with the name of the
program appearing as the first element (argv[0]).
It is important to realize that the arguments will be
captured as strings (arrays of characters); the functions
atoi and atof can be used to convert a string to,
respectively, an integer and a double.