I see in this topic C++ convert hex string to signed integer that boost::lexical_cast can convert hexadecimal inside string to another type (int, long...)
but when I tried this code:
std::string s = "0x3e8";
try {
auto i = boost::lexical_cast<int>(s);
std::cout << i << std::endl; // 1000
}
catch (boost::bad_lexical_cast& e) {
// bad input - handle exception
std::cout << "bad" << std::endl;
}
It ends with a bad lexical cast exception !
boost doesn't support this kind of cast from string hex to int ?
As per the answer from C++ convert hex string to signed integer:
Also, as per
boost::lexical_cast<>documentationSo for more involved conversion,
std::stringstreamis recommended.If you have access to C++11 compiler, you can use
std::stoito convert any hexadecimal sting to an integer value.stoiprototype is:Your program can be converted to
And the output will be