C/C++ Command-line argument "arg"

C/C++ Command-line arguments 

Hii
guys today's topic is command-line arguments as we all know In c and c++ its possible to pass some value from the command-line to our program when they are executed.These values are called
Command-line arguments and many times they are important for our program especially when we want to control our program behavior from outside instead of hard coding those values inside the code.

Properties of Command Line Arguments:

  1. They are passed to main() function.
  2. They are parameters/arguments supplied to the program when it is invoked.
  3. They are used to control program from outside instead of hard coding those values inside the code.
  4. argv[argc] is a NULL pointer.
  5. argv[0] holds the name of the program.
  6. argv[1] points to the first command line argument and argv[n] points last argument.
how to define command line arguments

we all know The most important function in C/C++  is main() function..we mostly defined main() function with a return type int and without parameters.
some thing like  this

int main()
{
//main()
}

To pass command line arguments, we define main() function with two arguments:
first argument is the number of command line arguments and second is list of command-line arguments.

Example:

int main(int argc, char *argv[]) { 
/*
function with arguments
*/ 
}

or

int main(int argc, char **argv[]) { 
/* 
function with arguments
*/
 }

argc:

argc (ARGument Count) is int and stores number of command-line arguments passed by the user including the name of the program. So if we pass a value to a program, value of argc would be 2 (one for argument and one for program name)

NOTE: The value of argc should be non negative.

argv

argv(ARGument Vector) is array of character pointers listing all the arguments.
If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will contain pointers to strings.
Argv[0] is the name of the program , After that till argv[argc-1] every element is command -line arguments.

Sample Code of c:

#include <stdio.h>
#include<stdlib.h>

int main( int argc, char *argv[] ) 
{

   if( argc == 2 )
   {
      printf("The argument supplied is %s\n", argv[2]);
   }
   else if( argc > 2 )
   {
      printf("Too many arguments supplied.\n");
   }
   else
   {
      printf("One argument expected.\n");
   }
}

Sample code of C++:

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
    cout << "You have entered " << argc
         << " arguments:" << "\n";
    for (int i = 0; i < argc; ++i)
 
        cout << argv[i] << "\n";
    return 0;
}

Facebook link: https://www.facebook.com/TeamSAOP/

Thank you

Comments