c++ - How to use argparse with integer argument values? - Stack Overflow

admin2025-04-17  0

I'm getting a std::bad_any_cast exception from the following argument parsing code which uses argparse.

argparse::ArgumentParser argument_parser("program name");
argument_parser.add_argument("--port")
    .help("port number")
    .required();
argument_parser.parse_args(argc, argv);

const auto port_number = argument_parser.get<int>("port");

As far as I'm aware, I don't need to do anything special for an integer type argument compared with a std::string type argument. (At least I don't see anything in the README page which suggests this.)

Link to argparse can be found here.

I'm getting a std::bad_any_cast exception from the following argument parsing code which uses argparse.

argparse::ArgumentParser argument_parser("program name");
argument_parser.add_argument("--port")
    .help("port number")
    .required();
argument_parser.parse_args(argc, argv);

const auto port_number = argument_parser.get<int>("port");

As far as I'm aware, I don't need to do anything special for an integer type argument compared with a std::string type argument. (At least I don't see anything in the README page which suggests this.)

Link to argparse can be found here.

Share asked Mar 8 at 20:57 user2138149user2138149 17.7k30 gold badges150 silver badges296 bronze badges 2
  • Reading quickly into readme, it seems that you need get<int>("--port")? See this example code: github/p-ranav/… – Yksisarvinen Commented Mar 8 at 21:05
  • Looks like you need to add scan github/p-ranav/… – Alan Birtles Commented Mar 8 at 21:08
Add a comment  | 

1 Answer 1

Reset to default 0

Apparently .scan<'i', int> is required.

argument_parser.add_argument("--port")
        .help("port number")
        .required()
        .scan<'i', int>();
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744885265a272494.html

最新回复(0)