Widget HTML Atas

C example on how to use command line arguments

In this simple example we will see how to use the command line arguments in our C programs.
Well, we all noticed that main() get two parameters.
int main(int argc, char *argv[]);
argc is an integer representing the size of argv[]
argv is a table of pointer to chars ( Strings )
Below is a simple calculator which takes as arguments two numbers and prints the sum.
The code is:

#include <stdio.h>

int main(int argc, char *argv[]) {
if ( argc != 3) {
printf("Usage:\n %s Integer1 Integer2\n",argv[0]);
}
else {
printf("%s + %s = %d\n",argv[1],argv[2], atoi(argv[1])+atoi(argv[2]));
}
return 0;
}

Now lets explain the code:
line 4 : we check if the user passed two arguments to the program. We actually need two arguments but in C the first argument ( argv[0] ) is the name of our program, so we need two more.
line 5 : If the user didn't pass two arguments we print the usage of our program and exit
line 8 : Using atoi() function we convert pointers to char (string) to decimal numbers and display their sum

Example without arguments

C:\>ArgumentCalculator.exe
Usage:
ArgumentCalculator.exe Integer1 Integer2

C:\>

Example with two arguments

C:\>ArgumentCalculator.exe 123456789 987654322
123456789 + 987654322 = 1111111111

C:\>


In addition to the above the code to print all the arguments is:

#include <stdio.h>

int main(int argc, char *argv[]) {
for(int i = 0 ; i<argc ; i++)
printf("\nArgument %d: %s", i, argv[i]);
return 0;
}

No comments for "C example on how to use command line arguments"