Vadim Ostanin
Vadim Ostanin

Reputation: 69

Lexical_cast throws exception

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;
    }
}

Upvotes: 0

Views: 520

Answers (1)

Abhishek Sinha
Abhishek Sinha

Reputation: 490

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!

Upvotes: 1

Related Questions