Reputation: 1047
How can I parse arguments without the hyphen in C?
I.e. virsh install vm
or
git pull origin master
When I tried it out, if there is no -
prefix, everything just gets ignored and argc
returns 1
(argv[0]
is the program call).
I'm using Linux, but it would be nice if there was a cross platform method to achieve this.
UPDATE: the problem was me using a #
in front of the first argument, I was trying to pass in #XX eg number_program #12. Needless to say this doesn't work.
Upvotes: 0
Views: 1787
Reputation: 86535
argv
contains the program name and the arguments to the program, in the order they were given in the command line.* Hyphens aren't special; they just make it easy for both people and computers to separate options from other args.
If you want to interpret args a certain way, that's your prerogative. That's what git
does, basically interpreting argv[1]
(if it exists, of course) as the name of a subcommand. And you don't need any libraries in order to do that. You just need to decide how you want the args interpreted.
* Modulo some cross-platform differences in how args are parsed; *nix typically does some pre-parsing for you and expands wildcard patterns, for example. You won't have 100% cross-platform compatibility unless you understand those differences and are ready for them.
Upvotes: 1
Reputation: 924
Are you using some library to parse the arguments for you? There is no special 'hyphen' arguments when passing in parameters to a C program specifically. Parse argv however you like.
For example:
#include <stdio.h>
int main(int argc, char **argv)
{
int i;
for(i=0; i<argc; i++) {
//dont do this without proper input validation
printf("%s\n", argv[i]);
}
return 0;
}
Example run:
$ ./a.out test test test -hyphen
./a.out
test
test
test
-hyphen
Upvotes: 2