Reputation: 61
I am using a function from a library that calls for the (argc,argv) command line functions from the main program to be passed directly to it; however, I only want to pass some arguments to it with the rest being evaluated in the main code not function. Below is a sample of the main code with evaluating arguments.
int main(int argc,char** argv)
{
// Evaluate arguments
if ( argc > 9 ) {
PrintUsage();
return 1;
}
G4String input;
G4String macro;
G4String physicslist;
for ( G4int i=1; i<argc; i=i+2 ) {
if ( G4String(argv[i]) == "-i" ) macro = argv[i+1];
else if ( G4String(argv[i]) == "-l" ) physicslist = argv[i+1];
else if ( G4String(argv[i]) == "-g" ) input = argv[i+1];
else if //pass the rest of the arguments to function below
G4MPImanager* g4MPI = new G4MPImanager(argc,argv);
Any other arguments not evaluated above I want to pass to the function from an outside library, which requires being called as shown.
Thanks!
Upvotes: 0
Views: 4790
Reputation: 264381
Create a vector of strings.
Erase the arguments you don't want from the vector.
You can then create a char*[]
from the vector very easily (at the size is trivial).
int main(int argc, char* argv[])
{
std::vector<char*> args(argv, argv+argc+1); // +1 to catch the last NULL at argv[argc]
for(auto loop = args.begin(); loop != args.end();)
{
if (/*Your Test 1 */) { /*STUFF 1*/ loop = args.erase(loop);}
else if (/*Your Test 2 */) { /*STUFF 2*/ loop = args.erase(loop);}
else { ++loop; /* If you did not remove it increment loop*/ }
}
// args.size() -1 becuase we have the extra NULL as the last argument.
// and argv[arc] should be null
// &args[0] is the address of the first member.
// vector keeps its data in contiguous memory so will look like an array
G4MPImanager* g4MPI = new G4MPImanager(args.size() - 1, &args[0]);
}
Upvotes: 2
Reputation: 154886
argv
is simply an array of char pointers terminated by a final NULL
pointer. You can create your own using my_argv = new char *[number_of_items + 1]
, where number_of_items
is the number of arguments you want to cherry-pick from "real" argv
(or your own strings). Such array can be passed to G4MPIManager
constructor instead of the actual argv
received in main()
.
Additional notes:
Don't forget to terminate argv
with a NULL pointer.
The first member of argv
, argv[0]
, will be expected to hold the "program name" and as such will be either ignored or only used to prefix diagnostic messages. Simply reuse the argv[0]
you get from main()
.
argc
should be such that argv[argc] == NULL
, i.e. the same as the number_of_items
above. Given that the argv
array must contain program name as first member, argc
will never be 0.
Upvotes: 2
Reputation: 444
You just have to construct new pair of argc and argv for whatever your i
is and then pass it to your function.
int newArgc = argc - i;
char** newArgv = &argv[i];
G4MPImanager* g4MPI = new G4MPImanager(newArgc, newArgv);
Upvotes: 0