Search code examples
c++functioncommand-line-argumentsprogram-entry-pointargs

How do I pass main args to some other function?


I was asked to write a program that gets 3 arguments from console and then uses those values to estimate some other function's value. I don't really know how can I use those values in some other function. I tried to do something like this, but it does not work:

#include <iostream>

using namespace std;

void logis(double a, double xz, int n){
    if (n == 0){return;}
    else{
        double x = a*xz(1-xz);
        logis(a, x, n-1);
        cout << n << "  " << x << endl;
    }
}

int main(int argc, char* argv[]){

    if (argc != 4){
        cout << "You provided 2 arguments, whereas you need to provide 3. Please provide a valid number of parameteres";
    }
    else{
        double a = argv[1];
        double x0 = argv[2];
        int n = argv[3];
        logis(a, x0, n);
    }

return 0;
}

Could anyone help me with that? I'm yet not concerned about if the function works or not, I just can't pass those values to my function.


Solution

  • You need to include the header <cstdlib>

    #include <cstdlib>
    

    and use the functions strtod and strtol (or atoi). For example

        double a = std::strtod( argv[1], nullptr );
        double x0 = std::strtod( argv[2], nullptr );
        int n = std::atoi( argv[3] );
    

    Here is a demonstrative program

    #include <iostream>
    #include <cstdlib>
    
    int main() 
    {
        const char *s1 = "123.45";
        const char *s2 = "100";
    
        double d = std::strtod( s1, nullptr );
        int x = std::atoi( s2 );
        std::cout << "d = " << d << ", x = " << x << '\n';
    
        return 0;
    }
    

    Its output is

    d = 123.45, x = 100
    

    if instead of the second parameter equal to nullptr to specify a valid pointer then you can also check that the string indeed contained a valid number. See the description of the functions.

    Another approach is to use standard string functions std::stod and std::stoi declared in the header <string> like for example

    double d = 0;
    
    try
    {
        d = std::stod( argv[1] );
    }
    catch ( const std::invalid_argument & )
    {
        // .. some action
    }