Skip to content

Commit 4840f38

Browse files
author
Matt Kline
committed
value::asLong will convert from string to long
This is less surprising behavior when calling asLong() on an arg expected to be an integer value.
1 parent 9de81eb commit 4840f38

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

docopt_value.h

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
#include <vector>
1414
#include <functional> // std::hash
1515
#include <iosfwd>
16+
#include <cstdio> // sscanf
1617

1718
namespace docopt {
1819

@@ -257,6 +258,16 @@ namespace docopt {
257258
inline
258259
long value::asLong() const
259260
{
261+
// Attempt to convert a string to a long
262+
if (kind == Kind::String) {
263+
// Doesn't guard against trailing characters,
264+
// but doing so (if desired) would be trivial.
265+
long ret;
266+
if (sscanf(variant.strValue.c_str(), "%ld", &ret) == 1) {
267+
return ret;
268+
}
269+
// else fall through
270+
}
260271
throwIfNotKind(Kind::Long);
261272
return variant.longValue;
262273
}

0 commit comments

Comments
 (0)