Table of Contents
Overview:
- Terms to know:
- Argument
- args
- argc/arg count
- New code:
- The amount of arguments passed into the program:
argCount - The list of arguments:
args - Argument with the program name:
args[0] - Arguments after that:
args[1],args[2], etc. - Store argument in string variable:
string VAR = string( args[1] ); - Store argument in float variable:
float VAR = stof( args[1] ); - Store argument in int variable:
int VAR = stoi( args[1] );
- The amount of arguments passed into the program:
1. What are program arguments?
Some command line programs take in arguments when you run them. For
example: ping yahoo.com . The ping program takes in a URL as an
argument, then the program will launch and attempt to send packets
of information to the URL and see if there's a response.
We can also write comamnd line programs with arguments. To do this, we need to add a couple of arguments to main:
int main( int argCount, char* args[] ) { }
In this case, any text given after the program name will be stored
in args[1] and after (the program name is in args[0].)
char* args[] is an array of c-style strings, though we can convert
them into other data types. The int argCount tells us how many
arguments were passed into the program. If the user doesn't pass
in enough arguments, we could display an error message and what we
expect the arguments to be.
For the time being, don't worry about "int", "char*", or "[ ]", but we will learn about these later. The arguments item is essentially a list of input items passed to the program. argCount will also contain the amount of arguments passed in. So, if a program is run like this:
./program ONE two THREE
Then it would have 4 total arguments (the program name counts as one), with "ONE" being argument #1, "two" being argument #2, and "THREE" being argument #3.
Review 1. Program arguments…
Review 2. Let's say a program named factorial is run like this:
./factorial 5
Identify each argument
Review 3. Let's say a program named add is run like this:
./add 2 3
Identify each argument
2. Converting arguments to different types
We can convert the arguments to different data types. The following code snippet shows examples:
int main( int argCount, char* args[] ) { if ( argCount < 5 ) { cerr << "Not enough arguments!" << endl; return 1; } int myInteger = stoi( args[1] ); float myFloat = stof( args[2] ); string myString = string( args[3] ); char myChar = args[4][0]; }
Generally in the starter code I'll handle checking for enough arguments and set up the input variables and cast the arguments to them, so you won't have to worry about this part of a program's setup.
Review 4. Identify the commands used.