docopt / docopt.cpp

C++11 port of docopt
Boost Software License 1.0
1.05k stars 146 forks source link

Integer arguments are parsed as strings #27

Closed mrkline closed 4 years ago

mrkline commented 9 years ago

Integer arguments are always parsed by docopt::docopt as strings. For example:

// In naval_fate.cpp
int main(int argc, const char** argv)
{
    std::map<std::string, docopt::value> args = docopt::docopt(USAGE, 
                                                  { argv + 1, argv + argc },
                                                  true,               // show help if requested
                                                  "Naval Fate 2.0");  // version string

    for(auto const& arg : args) {
        std::cout << arg.first << ": " << arg.second << std::endl;
    }
    // Test
    if (args["<x>"]) std::cout << args["<x>"].asLong(); // Throws here
    if (args["<y>"]) std::cout << args["<y>"].asLong();

    return 0;
}

throws, giving

terminate called after throwing an instance of 'std::runtime_error' what(): Illegal cast to long; type is actually string

By the principle of least astonishment, I would think that calling asLong on an integral argument would give me a long with no hassle. But some quick inspection of docopt_value.h and docopt.cpp shows that the value's internal union is fed a string, and toLong throws its hands up instead of attempting some conversion.

Forgive me if I'm missing something obvious (as I haven't dug through the code thoroughly). Is this expected behavior? Of course you can always parse the values yourself with istringstream or sscanf, but doing so is a bit of a pain, especially for a library focused on simplicity and expressiveness.

jaredgrubb commented 8 years ago

Yes, I think the "asLong" function should be renamed.

The official 'docopt' version doesnt try to create numbers out of arguments; the numbers only happen on presence/counting args (eg, "--help" or "-vvv"). I think we should rename this so that it's clear what is happening.

jaredgrubb commented 4 years ago

I think this is stale now that #28 is integrated. Please reopen if you disagree.