Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 702
lovespeed Avatar asked Jul 03 '12 17:07

lovespeed


People also ask

What is a command line input?

They are parameters/arguments supplied to the program when it is invoked. They are used to control program from outside instead of hard coding those values inside the code. argv[argc] is a NULL pointer. argv[0] holds the name of the program.

How do you give a Python script a command line input?

To take input (or arguments) from the command line, the simplest way is to use another one of Python's default modules: sys. Specifically, you're interested in sys. argv, a list of words (separated by space) that's entered at the same time that you launch the script.

What function does Python use to get the input from the command line?

Python provides developers with built-in functions that can be used to get input directly from users and interact with them using the command line (or shell as it is often called). In Python 2, raw_input() and in Python 3, we use input() function to take input from Command line.

Can JavaScript take input from console?

To get the user's input from the web browser is easy by using JavaScript prompt() method. However, what is not understandable is using JavaScript which runs only the browser, to get input from a systems command line. Doing this is possible using NodeJS.


1 Answers

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.

like image 151
Sergey Kalinichenko Avatar answered Oct 20 '22 16:10

Sergey Kalinichenko