Command-line Arguments

Command-line Arguments

Some programs executed from the command line accept additional arguments. For example, in a Microsoft Windows command prompt the command…

copy count.cpp count2.cpp
cp count.cpp count2.cpp

These filenames are called command-line arguments. They are provided in addition to the program’s name. Command-line arguments allow the user to customize in some way the behavior of the program when launching it.

#include <iostream>

int main(int argc, char * argv[]) {
    for (int i = 0; i < argc; i++)
        std::cout << '[' << argv[i] << "]\n";
C:\Code>cmdlineargs -h 45 extra

The program did not print the first line shown in this program run. The command shell printed C:\Code> awaiting the user’s command, and the user typed the remainder of the first line. In response, the program printed four lines that follow. The argument char *argv[] indicates argv is an array of C strings. Notice that argv[0] is simply the name of the file containing the program. argv[1] is the string “-h”, argv[2] is the string “45”, and argv[3] is the string “extra”.

#include <iostream>

#include <sstream>

#include <cmath>

int main(int argc, char * argv[]) {
    if (argc < 3)
        std::cout << "Supply range of values\n";
    else {
        int start, stop;
        std::stringstream st(argv[1]),
        st >> start;
        sp >> stop;
        for (int n = start; n <= stop; n++)
            std::cout << n << " " << sqrt(n) << '\n';

Since the command-line arguments are strings, not integers, must convert the string parameters into their integer equivalents. The following shows some sample runs of :

Supply range of values
C:\Code>sqrtcmdline 2
Supply range of values
C:\Code>sqrtcmdline 2 10
2 1.41421
3 1.73205
4 2
5 2.23607
6 2.44949
7 2.64575
8 2.82843
9 3
10 3.16228

Vectors vs. Arrays

It is important to note is that arrays are not objects and, therefore, have no associated methods. The square bracket notation when used with arrays does not represent a special operator method. The square bracket array access notation is part of the core C++ language inherited from C.

A vector and its associated array AndroWep-Tutorials
A vector and its associated array AndroWep-Tutorials