Command line login

I have a C ++ program that I run for many parameter values. I want to do the following: Let's say I have two parameters:

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

Now after compilation I want to run it as

 ./output.out 2.2 5.4 

So, 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 this because I am running the program in a cluster.

+6
source share
5 answers

You need to use command line arguments in 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 the parameters using atof ; you can use stringstream .

+20
source

If you want to use command line options, then no, you are not using cin , since it's 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 now you have argv , which is an array of a pointer to char , with each pointer pointing to the argument passed. The first argument is usually the path to your executable file, the subsequent arguments are all that was passed when your application started, in the form of pointers to char .

In this case, you will need to convert char* to double .

+11
source

For which command line arguments:

 #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 } 
+3
source

Have you looked to increase program parameters ?

This will lead to command line arguments, like so many others, and prompt you to provide a very consistent, clean and extensible command line interface.

+3
source

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

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

where the values โ€‹โ€‹of the argv[] array contain command line variables like char* , which you will need to convert to floats or doubles in your case

0
source

Source: https://habr.com/ru/post/919607/


All Articles