Chapter 6. Boost.LexicalCast

    Example 6.1. Using boost::lexical_cast

    uses streams internally to perform the conversion. Therefore, only types with overloaded operator<< and operator>> can be converted. However, boost::lexical_cast can be optimized for certain types to implement a more efficient conversion.

    1. #include <boost/lexical_cast.hpp>
    2. #include <string>
    3. #include <iostream>
    4. {
    5. {
    6. int i = boost::lexical_cast<int>("abc");
    7. }
    8. catch (const boost::bad_lexical_cast &e)
    9. {
    10. std::cerr << e.what() << '\n';
    11. }

    If a conversion fails, an exception of type boost::bad_lexical_cast, which is derived from , is thrown. Example 6.2 throws an exception because the string “abc” cannot be converted to a number of type int.