BDE 4.14.0 Production release
|
Provide conversions from text into fundamental numeric types.
This component provides a namespace, bdlb::NumericParseUtil
, containing utility functions for parsing ascii text representations of numeric values into the corresponding value of a fundamental C++ type (like int
or double
).
None of the parsing functions in this component consume leading whitespace. For parsing to succeed, the sought item must be found at the beginning of the input string.
The following two subsections describe the grammar defining the parsing rules.
The following grammar is used to specify regular expressions:
The parsing functions provided by bdlb::NumericParseUtil
typically return an optional, second, output parameter named remainder
. The output parameter remainder
is loaded with a string reference starting at the character following the last character successfully parsed as part of the numeric value, and ending at the character one past the end of the input string. If the entire input string is parsed successfully, remainder
is loaded with an empty string reference. However, if the parse function is not successful (i.e., it returns a non-zero error status), then it will not modify the value of remainder
.
The conversion from text to values of type double
results in the closest representable value to the decimal text. Note that this is the same as for the standard library function strtod
. For example, the ASCII string "3.14159" is converted, on some platforms, to 3.1415899999999999.
The strtod
function is locale-dependent. It uses the LC_CTYPE
and LC_NUMERIC
locale categories from the C standard global locale established by setlocale
. LC_CTYPE
is used by strtod
to skip leading whitespace, whereas LC_NUMERIC
is used in the actual parsing of the number. Our implementation forbids leading whitespace. When verifying the lack of leading whitespace we use both our own locale-independent character classification function (in case LC_CTYPE
would not classify ASCII whitespace properly), as well as the C global locale-dependent bsl::isspace
to ensure that strtod
will not skip some special whitespace characters and parse a string as fully-a-number by mistake. That allows us to ignore the LC_CTYPE
locale category, however we still have to require LC_NUMERIC
to be set to the "C" locale for strtod
itself.
The IEEE-754 (double precision) floating point format supports the following special values: Not-a-Number (NaN) and Infinity, both in positive or negative. parseDouble
allows expressions for both:
+
) or minus (-
) sign+
) or minus (-
) signIn this section, we show the intended usage of this component.
Suppose that we have a string_view that presumably contains a (not necessarily NUL terminated) string representing a 32-bit integer value and we want to convert that string into an int
(32-bit integer).
First, we create the string:
Then we create the output variables for the parser:
Next we call the parser function:
Then we verify the results: