27
C++ A Beginner’s Guide by Herbert Schildt
char *argv[];
You can access the individual arguments by indexing argv. The following program demonstrates how to
access the command-line arguments. It displays all of the command-line arguments that are present
when it is executed.
// Display command-line arguments.
Introducing Functions
For example, if the program is called ComLine, then executing it like this:
C>ComLine one two three
causes the following output:
ComLine
one
two
three
C++ does not stipulate the exact nature of a command-line argument, because host environments
(operating systems) vary considerably on this point. However, the most
common convention is as
follows: each command-line argument must be separated by spaces or tabs. Often commas, semicolons,
and the like are not valid argument separators. For example,
one, two, and three
is made up of four strings, while
one,two,and three
has two strings—the comma is not a legal separator.
28
C++ A Beginner’s Guide by Herbert Schildt
If you need to pass a command-line
argument that does, in fact, contain spaces, then you must place it
between quotes. For example, this will be treated as a single command-line argument:
"this is one argument"
Keep in mind that the examples provided here apply to a wide variety of environments, but not
necessarily to yours.
Usually, you will use argc and argv to get initial options or values (such as a filename) into your program.
In C++, you can have as many command-line arguments as the operating system will allow. Using
command-line arguments will give your program a professional appearance and facilitate the program’s
use in batch files.
Passing Numeric Command-Line Arguments
When you pass numeric data as a command-line argument to a program, that data will be received in
string form. Your program will need to convert it into the binary, internal format using one of the
standard library functions supported by C++. Three of the most commonly used functions for this
purpose are shown here:
Each is called with a string containing a numeric value as an argument. Each uses the header
.
The following program demonstrates the conversion of a numeric command-line argument into its
binary equivalent. It computes the sum of the two numbers that follow its name on the command line.
The program uses the atof( ) function to convert its numeric argument into its internal representation.
29
C++ A Beginner’s Guide by Herbert Schildt
To add two numbers, use this type of command line (assuming the program is called add):
C>add 100.2 231
Do'stlaringiz bilan baham: