boost lexical_cast

Boost.LexicalCast provides a cast operator, boost::lexical_cast, that can covert numberes from strings to numeric types like int or double.

#include <boost/lexical_cast.hpp>
#include <string>
#include <iostream>

int main() {
  std::string s = boost::lexical_cast<std::string>(123);
  std::cout << s << std::endl;
  double d = boost::lexical_cast<double>(s);
  std::cout << d << std::endl;
  return 0;
}

boost::lexical_cast uses streams internally to perform the conversion. Therefore, only types with overloader operator<< and operator>> can be converted.

If a conversion fails, an exception of type boost::bad_lexical_cast, which is derived from std::bad_cast, is thrown.

原文地址:https://www.cnblogs.com/sssblog/p/10978528.html