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

Possible duplicate:
Passing arguments to the C program from the command line.

mypro parameter

At startup, as described above, how to get the parameter in mypro main():

#include <iostream>

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

How to implement pseudo code above?

+3
source share
9 answers

Just add (int argc, char *argv[])to your main function. argc contains 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 (for example, an executable file). Therefore, the first argument is actually argv [1].

+12
source

Your function should use the second of two allowed basic C ++ function signatures:

int main(void)

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

argc - count, argv - .

. .

+3

, , , :

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

}

, argc. , , .

+2

:

int main(int argc, char** argv){

argc - , argv - , ( 0, ). 1 argv.

+2
#include <iostream>


using namespace std;

int main(int argc, char* argv[]) {
   for(int i = 1; i < argc; i++)
      cout << atoi(argv[i]) << endl;
   return 0;
} 

argc argv [i] .

argv [0] = ' '

+2

main() : argc argv . , argv[0] .

, : ./prog hello world:

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

​​ , :

#include <iostream>
#include <string>

int main(int argc, char **argv) {
    std::string arg = "default";
    if (argc >= 2) {
        default = argv[1]
    }
    return 0;
}
+2

main : int argc char ** argv, .

argc - , , argv ( argv [0] "mypro" ).

,   int main (int argc, char ** argv) {..}

+1
source

You need to use this main declaration:

int main(int argc, _TCHAR* argv[])
{
    if (argc > 1)
    {
        str = argv[1];
    }
}

argv[0] is the name of the executable, so the parameters begin with argv[1]

+1
source

On Windows, instead of using Unicode arguments, use the following signature:

int wmain(int argc, wchar_t** argv)
+1
source

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


All Articles