在进行编码时经常需要将整型数转化为string, 或者string转成整型数,或者char[]转化为整数。 boost的lexical_cast基本上提供了我们需要的所有常用的转化功能。相比一般的转换,其优点在于 可在任意可输出到stringstream的类型和任意可从stringstream输入的类型间转换。
一个开胃的例子:string to int, int i = boost::lexical_cast<int>("123");
More general 用法:
template<typename Target, typename Source> 定义Target 和 Source,两种类型
Target t;Source source; //定义对象,source应该有初始值
把Source类型转成Target, 只需要简单的这样写:
Target t = boost::lexical_cast<Target>(source); //转换不成功的时候,lexical_cast会抛出一个bad_lexical_cast的异常,严谨的用法应该是 如一下例子:
include <iostream>
#include <string>
#include "boost/lexical_cast.hpp"
template <typename T> std::string to_string(const T& arg) {
try {
return boost::lexical_cast<std::string>(arg);
}
catch(boost::bad_lexical_cast& e) {
return " ";
}
}
int main() {
std::string s=to_string(412);
s=to_string(2.357);
}
参考: http://www.ok2002.com/document/c-and-plus/c-plus-plus-boost-standard/0321133544/ch02lev1sec5.html