CLIUtils / CLI11

CLI11 is a command line parser for C++11 and beyond that provides a rich feature set with a simple and intuitive interface.
https://cliutils.github.io/CLI11/book/
Other
3.4k stars 354 forks source link

Could not convert: integer option passed as a string with an extra space after the value #1094

Open aphecetche opened 1 day ago

aphecetche commented 1 day ago

A very simple example (using version 2.4.2) "fails" when called with -i "42 " (note the extra space at the end of the string), but works fine for e.g. -i " 42" (space before the integer) (and of course for the more natural way of calling it directly with an integer, e.g. -i 42

Is that a feature or a bug ? Knowing that e.g. std::stoi convert both " 42" and "42 " just fine, I'd call it a bug, but there might be something obvious I'm missing here ?

see e.g. https://godbolt.org/z/jad4MfsKP to run it

#include <iostream>
#include "CLI/CLI.hpp"

int main(int argc, char** argv)
{
  int value{0};

  CLI::App app{"basic cli example"};

  app.option_defaults()->always_capture_default();

  app.add_option("-i", value);

  try {
    app.parse(argc, argv);
  }
  catch (const CLI::ParseError& error) {
    std::cout << "CLI11 " << error.what() << "\n";
    return app.exit(error);
  }

  std::cout << "value=" << value << "\n";
}
phlptp commented 19 hours ago

it is mostly on purpose. Internally it uses std::strtoll to do the conversion and it has a check to make sure that is converts the entire string to an integer or other number. std::stoi ignores trailing characters as well so it converts " 523badNUMBER" just as well as "523" This is generally not what is desired, so the general philosophy has been that if it can't use all the characters in the conversion then something is wrong.

The exact question of whether trailing spaces should be allowed is probably debatable.

aphecetche commented 18 hours ago

ok, I see. Considering that "523badNUMBER" is not a valid number indeed makes sense to me.

But rejecting "523 " is a bit more surprising (and probably less obvious to spot from the user point of view).