Input from command line

33,535

Solution 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.

Solution 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.

Solution 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
}

Solution 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.

Share:
33,535
lovespeed
Author by

lovespeed

Updated on July 09, 2022

Comments

  • lovespeed
    lovespeed almost 2 years

    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.