...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
lexical_cast<int8_t>("127")
throw bad_lexical_cast
?
int8_t
is a typedef
to char
or signed
char
. Lexical conversion to
these types is simply reading a byte from source but since the source
has more than one byte, the exception is thrown. Please use other
integer types such as int
or short int
.
If bounds checking is important, you can also call boost::numeric_cast
: numeric_cast<int8_t>(lexical_cast<int>("127"));
lexical_cast<unsigned char>("127")
throw bad_lexical_cast
?
int
or short int
.
If bounds checking is important, you can also call boost::numeric_cast
: numeric_cast<unsigned char>(lexical_cast<int>("127"));
lexical_cast<std::string>
of an int8_t
or uint8_t
not do what
I expect?
lexical_cast<std::string>(static_cast<int>(n));
ios_base::skipws
flag of an underlying stream object.
It breaks my operator>>
that works only in presence of this flag. Can you remove code that resets
the flag?
operator>>
conform to the standard. Read a good C++ book, study std::sentry
and ios_state_saver
.
std::cout << boost::lexical_cast<unsigned int>("-1");
does not throw, but outputs 4294967295?
boost::lexical_cast
has the behavior of std::stringstream
,
which uses num_get
functions of std::locale
to convert numbers. If we look at the Programming languages — C++,
we'll see, that num_get
uses the rules of scanf
for conversions. And in the C99 standard for unsigned input value
minus sign is optional, so if a negative number is read, no errors
will arise and the result will be the two's complement.
boost::lexical_cast<int>(L'A');
outputs
65 and boost::lexical_cast<wchar_t>(L"65");
does not throw?
boost::lexical_cast
sees single wchar_t
character as unsigned short
.
It is not a boost::lexical_cast
mistake, but a limitation of compiler options that you use.
boost::lexical_cast<double>("-1.#IND");
throws boost::bad_lexical_cast
?
"-1.#IND"
is a compiler extension, that violates standard. You shall input
"-nan"
, "nan"
, "inf"
, "-inf"
(case
insensitive) strings to get NaN and Inf values. boost::lexical_cast<string>
outputs "-nan"
,
"nan"
, "inf"
, "-inf"
strings, when has NaN or Inf input values.
boost::lexical_cast
?
boost::iterator_range
for conversion. For example, if you whant to convert to int
two characters from a string
str
, you shall write
lexacal_cast<int>(make_iterator_range(str.c_str(),
str.c_str()
+ 2));
.