Chapter 6. Boost.LexicalCast

Boost.LexicalCast provides a cast operator, boost::lexical_cast, that can convert numbers from strings to numeric types like int or double and vice versa. boost::lexical_cast is an alternative to functions like std::stoi(), std::stod(), and std::to_string(), which were added to the standard library in C++11.

Example 6.1. Using boost::lexical_cast

  1. #include <boost/lexical_cast.hpp>
  2. #include <string>
  3. #include <iostream>
  4. int main()
  5. {
  6. std::string s = boost::lexical_cast<std::string>(123);
  7. std::cout << s << '\n';
  8. double d = boost::lexical_cast<double>(s);
  9. std::cout << d << '\n';
  10. }

The cast operator boost::lexical_cast can convert numbers of different types. Example 6.1 first converts the integer 123 to a string, then converts the string to a floating point number. To use boost::lexical_cast, include the header file boost/lexical_cast.hpp.

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.

Example 6.2. boost::bad_lexical_cast in case of an error

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

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