using argv

I want my program to receive a int on the command line, 1-9999. How do I check argv against specific values?
Hope the following piece of minimal code helps -- there should be enough in there for you to figure out the basics.

Note that in practice you'd want to check that the user actually entered a command line parameter and proceed accordingly. The way to do this is to check the value of argc. If it is 1 then no command line parameter was entered and the values of argv[i] for i>0 will be undefined (referencing, say, argv[2] in such an instance would be like referencing the 20th element of a 10 element array - not good).

For your purposes you may also want to check that the command line parameter was an integer and not a char.

You'll find it helpful to play around with this; try running the program with various command line parameters and see what prints out.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// CommandLine.cpp
// demonstrates the use of command line parameters
// for a nice reference on this;
// http://www.site.uottawa.ca/~lucia/courses/2131-05/labs/Lab3/CommandLineArguments.html

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    // argc gives you the NUMBER of command line parameters
    cout << "There were " << argc << " parameters\n";
    // argv is an array containing same;
    for (int i=0; i<argc; i++)
        cout << "Parameter " << i << " was " << argv[i] << "\n";

    // convert argv[1] to integer
    int cl_param;
    cl_param = atoi(argv[1]);

    // check argv[1] against a number;
    int my_var;

    cout << "\n\nEnter an integer between 1 and 9999: ";
    cin >> my_var;
    if (cl_param>my_var)
        cout << "\n\nThe command line parameter of " << cl_param
             << " is > " << my_var;
    if (cl_param<my_var)
        cout << "\n\nThe command line parameter of " << cl_param
             << " is < " << my_var;
    if (cl_param==my_var)
        cout << "\n\nThe command line parameter of " << cl_param
             << " = " << my_var;
    if (cl_param==0)
        cout << "\n\nDid you enter 0?";

    cout << "\n\n";
    system("PAUSE");
    return EXIT_SUCCESS;
}
Last edited on
Topic archived. No new replies allowed.