Input from command line

2019-04-07 19:16发布

问题:

I have a program in C++ which I run for many values of a parameter. What I want to do is the following: Let's say I have two parameters as:

int main(){
    double a;
    double b;
//some more lines of codes
}

Now after after I compile I want to run it as

./output.out 2.2 5.4

So that a takes the value 2.2 and b takes the value 5.4.

Of course one way is to use cin>> but I cannot do that because I run the program on a cluster.

回答1:

You need to use command line arguments in your main:

int main(int argc, char* argv[]) {
    if (argc != 3) return -1;
    double a = atof(argv[1]);
    double b = atof(argv[2]);
    ...
    return 0;
}

This code parses parameters using atof; you could use stringstream instead.



回答2:

If you want to use command line parameters then no, you don't use cin as it is too late. You need to change your main signature to:

int main(int argc, char *argv[]) {
    // argc is the argument count
    // argv contains the arguments "2.2" and "5.4"
}

So you now have argv which is an array of pointer to char, each pointer pointing to an argument that was passed. The first argument is typically the path to your executable, subsequent arguments are whatever was passed in when your application was launched, in the form of pointers to char.

You will need to convert the char*'s to doubles in this case.



回答3:

That's what command-line arguments are for:

#include <sstream>

int main(int argc, char *argv[])
{
    if (argv < 3)
       // show error
    double a, b;

    std::string input = argv[1];
    std::stringstream ss = std::stringstream(input);

    ss >> a;

    input = argv[2];
    ss = std::stringstream(input);

    ss >> b;

    // a and b are now both successfully parsed in the application
}


回答4:

Have you looked at boost program options?

It will take the command line arguments like many other are suggesting and let you provide a very consistent, clean and extensible command line interface.



回答5:

You can use this form of the main() function to get command line arguments

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

    } 

where the values of the argv[] array contain your command line variables as char* that you will need to convert to floats or doubles in your case