4

This short C++ program behaves in a way which baffles 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.1 and boost-1.58.0, I get:

terminate called after throwing an instance of 'boost::exception_detail::clone_impl >' what(): bad lexical cast: source type value could not be interpreted as target

Why can't Boost cast from string "-2" to signed char given that the value -2 is representable by this type?

quant_dev
  • 6,181
  • 1
  • 34
  • 57

1 Answers1

3

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);
T.C.
  • 133,968
  • 17
  • 288
  • 421
quant_dev
  • 6,181
  • 1
  • 34
  • 57