How to Use Command Line Parameters in C++

Command-line parameters are special words that convey technical information to a program during launch. A user can pass them externally from the command line or from a Windows interface such as the Run utility. A programmer has the option to pass them internally as arguments to the main() function of the program. This tutorial focuses on the latter method. Read on to learn how to use command line parameters in C++.

Things You'll Need

  • Basic C++
  • Microsoft Visual C++, Borland C++ Builder or other IDE
Show More

Instructions

    • 1

      Memorize the input arguments to the main() function. They are always two, and their convention is consistent across all programming environments. The first parameter is argc, which is an int type. The second parameter is argv, an array of C-style strings. A good way to think of it is as a two-dimensional array of char.

    • 2

      Understand the significance of argc and argv. Each element in argv contains a command-line parameter. The first string is the name of the C++ program. Argc is the number of strings in argv. So if you enter -p -g myprog.exe from the DOS console, argv[0] will be "myprog.exe," argv[1] will contain -p and argv[2], -g. The value of argc is 3 in this case.

    • 3

      Study the following C++ code snippet that prints the command-line parameters passed into main() to the standard output stream.

      int main() {

      for(int i = 0; i < argc; i++) {

      std::cout << argv[i] << std::endl;

      } // close loop

      } // close main

      Notice how the loop uses argc as the upper limit of the loop that iterates through the elements stored in argv.

    • 4

      Observe the output from the command line parameters used in the example in Step 2.

      myprog.exe

      -p

      -g

Tips & Warnings

  • Separate command line parameters by a space, as if they were words.

  • Most IDEs for software development provide a Compiler feature that lets the programmer enter run-time parameters.

  • Command line parameters can be either existing global constants or constants defined by the programmer.

Related Searches:

Resources

Comments

You May Also Like

Related Ads

Featured