Friday, January 25, 2013

A note on Command line argument

Arguments can be passed to any function in a program, including the main() function.

Arguments passed to main(), must be declared as part of the function’s definition. To standardize passing arguments to a main() function, only two  items are allowed: a number and an array. The number is an integer variable, typically named argc (short for argument counter), and the array is a one-dimensional list, which is, by convention, named argv (short for argument values). Figure D.3 illustrates these two arguments.
----------------------------------------------------------------------------------------------
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
    int i;
   
    cout << "\n The number of items on the command line is "
         << argc << endl << endl;
       
    for(i = 0; i < argc; i++)
    {
        cout << "the address stored in argv[" << i << "] is "
             << int (argv[i]) << endl; //dispaly address as an integer number
           
        cout << "the character pointed to is " << *argv[i] << endl;
    }
   
    return 0;
}

OUTPUT:
 ____________________________________________________________

 // A program that displays its command-line arguments

#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
    int i;
    cout << "\nThe following arguments were passed to main(): ";
   
    for (i = 0; i < argc; i++)
    {
        cout << argv[i] << " ";
    }
   
    cout << endl;
    return 0;
}

OUTPUT:
 

No comments:

Post a Comment