c++boostlexical-cast

boost::lexical_cast can convert hex inside string to int?


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 ?


Solution

  • As per the answer from C++ convert hex string to signed integer:

    It appears that since lexical_cast<> is defined to have stream conversion semantics. Sadly, streams don't understand the "0x" notation. So both the boost::lexical_cast and my hand rolled one don't deal well with hex strings.

    Also, as per boost::lexical_cast<> documentation

    The lexical_cast function template offers a convenient and consistent form for supporting common conversions to and from arbitrary types when they are represented as text. The simplification it offers is in expression-level convenience for such conversions. For more involved conversions, such as where precision or formatting need tighter control than is offered by the default behavior of lexical_cast, the conventional std::stringstream approach is recommended.

    So for more involved conversion, std::stringstream is recommended.

    If you have access to C++11 compiler, you can use std::stoi to convert any hexadecimal sting to an integer value.

    stoi prototype is:

    int stoi( const std::string& str, std::size_t* pos = nullptr, int base = 10 );
    

    Your program can be converted to

    int main() {
        std::string s = "3e8";
        auto i = std::stoi(s, nullptr, 16);
        std::cout << i << '\n';
    }
    

    And the output will be

    1000