Boost :: lexical_cast <signed char> can't handle negative numbers?

This short C ++ program behaves in a way that puzzles me:

#include <cassert>
#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>

int main(void) {
    signed char c = -2;
    assert(c == -2);
    c = boost::lexical_cast<signed char>(std::string("-2"));
    std::cout << c << "\n";
}

Using g++ 5.2.1and boost-1.58.0, I get:

ending the call after calling the instance 'boost :: exception_detail :: clone_impl>' what (): bad lexical cast: the value of the source type cannot be interpreted as target

Why can't Boost from line “-2” to signed charif value -2is represented by this type?

+4
source share
1 answer

The solution is to use Boost:

#include <boost/lexical_cast.hpp>
#include <boost/numeric/conversion/cast.hpp>
int tmp = boost::lexical_cast<int>(std::string("-2"));
char c = boost::numeric_cast<signed char>(tmp);
+3
source

Source: https://habr.com/ru/post/1620925/


All Articles