简体   繁体   中英

Passing C++ command line arguments inside main(), yet do the same job

Is there a way to keep the command line argument as standard and yet pass the argv internally inside the main?

Like, change this:

int main(int argc, char **argv) {
    App app(argc,argv);
    return app.exec();
}

to something like this:

int main(int argc, char **argv) {
    vector<string> argv ="arguments";
    int argc = X;
    App app(argc,argv);
    return app.exec();
}

When I have:

./a.out -a A -b B -c C

I know this is weird. I just want to find a workaround not to change the source code of a huge project and just run my command line arguments every time with only ./a.out .

Put each of your arguments in a char array, and then put pointers to those arrays into an array of pointers.

char arg1[] = "./a.out";
... 
char argN[] = "whatever";
char* argv[] = { arg1, ..., argN}

App app(N, argv);

You may be looking for

const char *myArgv[]={"-a","A","-b","B"};
int myArgc=4;
App app(myArgc,myArgv);
return app.exec();
std::vector<std::string> args(argv, argv+argc);

You may rename arguments passed to app as you wish to avoid a name conflict, for ex.

int main(int argc, char **argv) {
    vector<string> app_argv = /* contents */;
    int app_argc = app_argv.size() ;
    App app(app_argc, app_argv);
    return app.exec();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM