Command line arguments

From Tux
Revision as of 01:01, 26 January 2018 by Williams (talk | contribs) (Created page with "Command line arguments in C++ are a method of passing values to a program at the time of execution. To use command line arguments, your main body should be defined such that...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Command line arguments in C++ are a method of passing values to a program at the time of execution.

To use command line arguments, your main body should be defined such that it accepts two parameters

  • An integer value, typically called argc (argument count), which denotes the number of arguments (including the command used to execute the program)
  • An array of C-strings, typically called argv (argument vector), which contains the arguments
int main(int argc, char **argv)
// int main (int argc, char *argv[]) is another way to write this
{
     for (int i = 0; i < argc; i++)
          cout << argv[i] << endl;
}

This program will print out the command used to run the program (stored in the C-string argv[0]), and all command line arguments which are stored in the C-strings argv[1] to argv[argc - 1].