0

boost::lexical_cast throwing exception during converting string to int8_t, but int32_t - norm.

What can be wrong with int8_t ?

#include <iostream> #include <cstdlib> #include <boost/lexical_cast.hpp> int main() { try { const auto a = boost::lexical_cast<int8_t>("22"); std::cout << a << std::endl; } catch( std::exception &e ) { std::cout << "e=" << e.what() << std::endl; } } 
2
  • 1
    Question: Why does lexical_cast<unsigned char>("127") throw bad_lexical_cast? Answer: Lexical conversion to any char type 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<unsigned char>(lexical_cast<int>("127")); from boost reference. In your case int8_t is alias for char. Commented Jul 1, 2019 at 8:52
  • @rafix07 int8_t is an alias to signed char in all architecture I've seen so far. The problem is that Lexical Cast treats both signed char and unsigned char just like char, rather than integer types. IMHO, a very unhappy design. Commented May 18, 2022 at 6:47

1 Answer 1

1

For boost::lexical_cast, the character type of the underlying stream is assumed to be char unless either the Source or the Target requires wide-character streaming, in which case the underlying stream uses wchar_t. Following types also can use char16_t or char32_t for wide-character streaming

Boost Lexical Cast

So after doing below changes in your code:

#include <iostream> #include <cstdlib> #include <boost/lexical_cast.hpp> int main() { try { const auto a = boost::lexical_cast<int8_t>("2"); const auto b = boost::lexical_cast<int16_t>("22"); std::cout << a << " and "<< b << std::endl; } catch( std::exception &e ) { std::cout << "e=" << e.what() << std::endl; } return 0; } 

Gives below output

2 and 22

So, I feel that each character is taken as char.

So, for const auto a = boost::lexical_cast<int16_t>("2"); 2 is taken as single char which require int8_t.

And, for const auto b = boost::lexical_cast<int16_t>("22"); 22 is taken as two char values which require int16_t.

I hope it helps!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.