2

I am just learning about command line arguments in my class and I do not fully understand them yet. I understand that they are stored in *argv[], and are counted by argc, but I do not understand their purpose or where they come from. I have attempted to write a program in C ++ to find the sum of command line arguments input by a user and have included the code below, but I have no idea if it is correct or how I would even test it. If someone could give me a simple description of what they are and how to access them it would be greatly appreciated.

#include <iostream>
#include <cstdlib>
using namespace std;

int main(int argc, char *argv[])
{
    double sum = 0;
    for(int counter = 0; counter < argc; counter ++)
    {
        sum += atof(argv[counter]); //compact form of :  sum = sum + atof(argv[counter]);
    }
    cout << "Sum = " << sum << endl;
}
manish
  • 1,450
  • 8
  • 13
dff
  • 311
  • 2
  • 17

2 Answers2

7

It's correct, but not beautiful since first argument (argv[0]) is application-name, but it cannot be converted to double, so 0.0 will be returned, however it will be more correct to start from 1. And if you want sum you should use += operator.

for(int counter = 1; counter < argc; counter ++)
{
    sum += atof(argv[counter]);
}
ForEveR
  • 55,233
  • 2
  • 119
  • 133
2

You can pass arguments to your Programm via the command line.

To do that you have to start your programm from a Console (CMD in Windows).

To pass arguments you simply do this from the Console (if the application is in the current directory):

myApplication arg1 arg2 arg3

The purpose is to pass values to your Programm when starting it. You e.g. pass a Path to a certain file that needs to be processed by your application or an option to start in Fullscreen etc.

Here is a simple Tutorial that explains command line argument.

Mailerdaimon
  • 6,003
  • 3
  • 35
  • 46