Domanda

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 achive this.

Thanks.

UPDATE: the problem was me using a # in fornt of the first argument, was trying to pass in #XX eg number_program #12, needless to say this doesnt work.

È stato utile?

Soluzione

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

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top