Baz
Baz

Reputation: 13155

std::string to int8_t

This gives a bad_lexical_cast exception:

int8_t i = boost::lexical_cast<int8_t>("12");

I would like to have an exception when the value doesn't fit in an int8_t.

How should I do this? Should I cast to an int first and throw an exception if the value falls outside the range -128 to 127?

I'm also interested in converting strings to uint8_t.

Upvotes: 2

Views: 4689

Answers (2)

ecatmur
ecatmur

Reputation: 157484

lexical_cast of a int8_t or uint8_t is treated as a char.

You can combine lexical_cast with numeric_cast to get what you want:

#include <boost/numeric/conversion/cast.hpp>
#include <boost/lexical_cast.hpp>

using boost::lexical_cast;
using boost::numeric_cast;

numeric_cast<int8_t>(lexical_cast<int>("128"));
numeric_cast<uint8_t>(lexical_cast<int>("256"));

Upvotes: 4

tenfour
tenfour

Reputation: 36896

Q: What does lexical_cast of an int8_t or uint8_t not do what I expect?

A: As above, note that int8_t and uint8_t are actually chars and are formatted as such. To avoid this, cast to an integer type first

Source:

http://www.boost.org/doc/libs/1_51_0/doc/html/boost_lexical_cast/frequently_asked_questions.html

Upvotes: 7

Related Questions