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:
Del.icio.us
#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;
}
10 comments:
IS VERY GOOD..............................
Nice Example. Things are becoming more and more simple with each day.
Thanks for sharing . very informative information. I will bookmarking this post.
http://mlmdevelopers.com/products/mlm-software/mlm-software-beta/features.html
Nice post for the beginners.Keep up posting such informative post.
It is another piece of your great work. Your site is very interesting and I read your posts each time something new appears. Thanks for your work.
Thanks nice work. However, you could have described the program more, I think.
You always
Socialkik do something better and different.. keep it up
Great post. I like this c++ a lot. Thanks for this good information.
Computer for dummy
I have been desperately looking for info about this and discovered your website via yahoo. It is undoubtedly one for my bookmarking! Keep up the good work I will pop back again soon.
Time and Attendance Software
Web Designing very informative information. I will bookmarking this post.
Post a Comment