Argv and Argc

The purpose of this assignment is to learn a little more about C++. Just like you can process the command line arguments sent to a bash shell script, you can also process the command line arguments sent to a C++ program.

Those arguments are passed to the "main" function. Main is passed two parameters - an integer that indicates the number of command line arguments, and an array of strings (the list of arguments).

For example, if we issued the command "a.out hi mom", then argc would equal 3, argv[0] would contain "a.out", argv[1] would contain "hi", and argv[2] would contain "mom".


Here is an example of a full program that processes command line arguments. The program computes the factorial of a value. Note that argv is an array of strings. So, even though the user types in a number, main is passed a string that must be converted into an integer.
/*************************************
Program to demo argv and argc
Calcultate the factorial of a number
*************************************/
#include <iostream>
#include <stdlib.h>
using namespace std;

int main(int argc, char *argv[])
{
   int input_val;   // integer version of argv[1]
   int output;      // the factorial
   int i;

   // test for correct number of arguments
   if (argc < 2)
     {
      cout << "Usage: fact num\n\n";
      exit(1);
     }

   // convert string to integer
   input_val = atoi(argv[1]);

   // test for not above 1
   if (input_val < 2)
     {
      cout << "value too small\n";
      exit (1);
     }

   // calculate the factorial
   output = 1;
   for (i=input_val; i>1; i--)
      output = output * i;
   cout << input_val << "! = " << output << endl;
}



Assignment 21

Write a VERY simple calculator that can add and subtract. The format of the command line arguments should be "calc integer operation integer". The two operations should be "+" and "-".

For example,

   >calc 
   Usage error: calc int operation int

   >calc 2 + 2
   4

   >calc 15 - 5
   10
This program is due one week from today.