lovespeed
lovespeed

Reputation: 5045

Input from command line

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.

Upvotes: 8

Views: 36253

Answers (5)

Zac
Zac

Reputation: 3285

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.

Upvotes: 3

mathematician1975
mathematician1975

Reputation: 21351

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

Upvotes: 0

Richard J. Ross III
Richard J. Ross III

Reputation: 55533

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
}

Upvotes: 4

Ed Swangren
Ed Swangren

Reputation: 124632

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.

Upvotes: 11

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

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.

Upvotes: 22

Related Questions