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?
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].
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With