Shell variable to c++ program as input

I have an Shell script which has few global variables
eg :

range=100;
echo "$range"

I want to use the same variable in my C++ program for example

 int main() 
 { cout << range << "\n"; }

i tried using this

int main(int argc, char *argv[])
{   cout << range << "\n"; }

but unsucessful, how should i proceed

Because C/C++ code is a compiled language, it's not aware of any variables you didn't define yourself at compile-time. In this case we need to use a library call to get shell variables, and even then we can't get all shell variables, only ones your shell has exported.

In shell:

export range=100

In program:

#include <stdlib.h>

int main(int argc, char *argv[])
{
       const char *range=getenv("range");

        if(range == NULL)
        {
                cout << "Range not available\n";
        }
        else
        {
                cout << "Range is " << range << "\n";
        }

        return(0);
}

Or you could do this:

myprogram $range
int main(int argc, char *argv[])
{
        if(argc < 2)
        {
                cout << "No argument\n";
                return(1);
        }

        cout << "First argument " << argv[1] << "\n";
        return(0);
} 

its showing

In function 'int main(int, char**)':
test_file.cpp:24: error: invalid operands of types 'const char*' and 'int' to binary 'operator*'

Did you #include <stdlib.h> ?

The code runs good, but when i am using the below code (a part of it for further processing )
it is throwing me the error

int range_m = range*1000;

error: invalid operands of types 'const char*' and 'int' to binary 'operator*'

Hi.

You're trying to assign a char * to an int.

A couple of easy options:

int range_m = atoi(range)*1000;

Or:

int range_m;
sscanf(range, "%d", &range_m);
range_m *= 1000;