Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get 1st parameter in main() in C++? [duplicate]

Tags:

c++

syntax

Possible Duplicate:
Pass arguments into C program from command line.

mypro parameter

When run like above,how to get the parameter in mypro's main() :

#include <iostream>

int main()
{
   char* str = "default_parameter";
   if(parameter_exists())str = parameter;
   ...
}

How to implement the pseudo code above?

like image 417
user198729 Avatar asked Nov 27 '22 10:11

user198729


2 Answers

Just need to add (int argc, char *argv[]) to your main function. argc holds the number of arguments, and argv the arguments themselves.

int main(int argc, char *argv[])
{
    std::string str = "default";
    if (argc > 1) { str = argv[1]; }
}

Note that the command is also included as an argument (e.g. the executable). Therefore the first argument is actually argv[1].

like image 72
Inverse Avatar answered Dec 08 '22 17:12

Inverse


When expecting command-line arguments, main() accepts two arguments: argc for the number of arguments and argv for the actual argument values. Note that argv[0] will always be the name of the program.

Consider a program invoked as follows: ./prog hello world:

argc    = 3
argv[0] = ./prog
argv[1] = hello
argv[2] = world

Below is a small program that mirrors the pseudocode:

#include <iostream>
#include <string>

int main(int argc, char **argv) {
    std::string arg = "default";
    if (argc >= 2) {
        default = argv[1]
    }
    return 0;
}
like image 41
Michael Koval Avatar answered Dec 08 '22 18:12

Michael Koval