How to write programs using command line arguments in a few easy steps

How to write programs using command line arguments in c

How to write programs using command line arguments in cIf you are having trouble understanding command line arguments then we two are both similar and different. How? First of all I had trouble understanding it too and the difference is I decided to leave it that way unlike you who googled and landed on to this page. It was out of sheer bad luck that I had to study command line arguments. I remember I was in class 10 at the time and I came late to class as usual. We were given the topics for the projects on that day and as a punishment I was handed out with this topic. 😥  It wasn’t totally bad luck as my partner was a beautiful girl who like me came in late and entered just a couple of  seconds before me. I never talked to her before and this was a great chance to impress her. I could already feel my friends were jealous.  😉

After the class I went to talk to her. She seemed pretty worried as she didn’t know anything about the topic. I had the same situation too but instead of telling her the truth I told her “Don’t worry I’ll teach you”. Also I invited myself to her house next day to teach her.  Only now I had to go home and study this topic and I was more than eager to do it. I went back home and I started to study from a book. After a couple of hours fiddling on this topic what I understood was instead of writing

int main()

I have to write

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

And argc counted the number of arguments and argv is an array of char pointers which contained the list of arguments. I tried testing a program from the book in DevCpp IDE but it was showing no outputs. There was this program in the book which I had to mug up.

A simple program using Command Line Arguments:


//program name: test.c
#include<stdio.h>
#include<conio.h>
int main(int argc, char *argv[])
{
 int i;
 for (i = 0; i < argc; i++)
 printf("%s \n", argv[i]);
 getch();
}

I was pretty low in confidence but I still decided to go to her house and teach her whatever little I understood. I was more relied on my charisma to impress her.

The next day I went to her house and I started to teach her with whatever little knowledge I had. The whole thing was going great and very soon the time came when I had to run the program on her computer which I failed to do and all the teachings fell apart. I even told her that this is how it worked at home and pretended that I didn’t know why it wasn’t working now. At that moment she told me this is not the way to run a program using command line arguments. You should only compile the program which creates the .exe file. Now you have to open Command Prompt. To do this Go to Run and write cmd. Then you go to the folder in the command prompt where you saved the .exe file and type the name of the program and some extra arguments. For example:


C:\CPrograms>test abc 123 def

I realized all this time she was kidding around to see what I do to impress her. You know that expression when you find a girl extremely attractive…maybe at that moment I had that expression. Alongside that I was also terribly embarrassed.

Meaning of argc and argv:

That time onward she became the teacher and I was her student. She told me the actual meaning of argc and argv. If we take the above example:


C:\CPrograms>test abc 123 def

argc counts the number of arguments (they are : test, abc, 123 and def) so a total of 4 arguments.
argv is an array containing the values (test, abc, 123 and def). Here argv[0] contains “test”, argv[1] contains “abc” and so on.

Write a program using command line arguments to calculate the sum of two numbers:

She showed me a program which will take input using command line arguments. It will take two numbers and output the sum of the numbers.


//program name: test.c
#include<stdio.h>
#include<conio.h>
int main(int argc, char *argv[])
{
 int firstNum = atoi(argv[1]);
 int secondNum = atoi(argv[2]);
 int sum = firstNum + secondNum;
 printf("%d + %d = %d", firstNum, secondNum, sum);
getch();

}

atoi is the function used to convert string into integer. As the arguments are in string format we need to convert it into int before doing any calculations. The argv[1] is the firstNum and the argv[2] is the secondNum. After compiling the program, type:


C:\CPrograms>test 12 34

The output will be:


12 + 34 = 46

Then we moved on to the project. She had an idea of creating a simple calculator using command line arguments. The user will enter the whole equation in the command line separated by spaces. For example:


C:\CPrograms>test 12 + 34 - 2

will give the output:


Result = 44

This way it will support all the simple operators. We succeeded to write the program. The project is given below as an example. Try to do it yourself, if you get stuck take a peek.  :mrgreen:

Write a Simple Calculator program using Command Line Arguments:


#include<stdio.h>
#include<conio.h>
int main(int argc, char *argv[]) {
 float result = atoi(argv[1]);
 int i;
 for (i = 3; i < argc; i = i + 2)
 switch (*argv[i-1]) {
 case '+':
 result = result + atoi(argv[i]);
 break;
 case '-':
 result = result - atoi(argv[i]);
 break;
 case '*':
 result = result * atoi(argv[i]);
 break;
 case '/':
 result = result / atoi(argv[i]);
 break;
 default:
 printf("Wrong Input");
 }
 printf("\nResult = %f", result);
}

And that was the last time I tried to teach a girl. We still talk about the fun we had while we did the project together and she never misses an opportunity to embarrass me even after so many years. The project was successful and our computer teacher found it very interesting. Finally this tutorial has come to an end. Hopefully you enjoyed reading it. If you have any problems regarding the tutorial use the comments section below. For more interesting tutorials and posts visit www.intechgrity.com.

4 comments

Leave a Reply