Reputation: 5084
referring to the beautiful solutions provided here, Convert string to int with bool/fail in C++,
I would like to cast a std::string to a 8 bit number (unsigned or signed)
The problem is that because 8 bit number is represented as a char so it is parsed wrong
(trying to parse anything above 1 digits - like 10 - fails)
Any ideas?
Upvotes: 0
Views: 9008
Reputation: 860
Use template specialization:
template <typename T>
void Convert(const std::string& source, T& target)
{
target = boost::lexical_cast<T>(source);
}
template <>
void Convert(const std::string& source, int8_t& target)
{
int value = boost::lexical_cast<int>(source);
if(value < std::numeric_limits<int8_t>::min() || value > std::numeric_limits<int8_t>::max())
{
//handle error
}
else
{
target = (int8_t)value;
}
}
Upvotes: 4
Reputation: 4112
Parse the number as int
and then cast it to uint8_t
. You may perform bound checks as well.
Upvotes: 1