在进行编码时经常需要将整型数转化为string, 或者string转成整型数,或者char[]转化为整数。当然这些函数都不难,完全可以自己实现,不过自己实现肯定要浪费一些时间进行编码和测试。boost的lexical_cast基本上提供了我们需要的所有常用的转化功能,需要的时候可以使用。
一个的例子如下:
#include "boost/lexical_cast.hpp"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char* argv[]) {
vector<int> nums;
for (int i = 1; i < argc; ++i) {
//char* 转int
nums.push_back(boost::lexical_cast<int>(argv[i]));
}
for (vector<int>::const_iterator it = nums.begin(); it != nums.end(); ++it) {
cout << *it << " ";
}
cout << endl;
string strNum = boost::lexical_cast<string>(23214223);
cout << "strNum = " << strNum << endl;
char* p = "Jesse Shang";
string strP = boost::lexical_cast<string>(p);
cout << "strP = " << strP << endl;
char* numP = "98432342";
int num = boost::lexical_cast<int>(numP);
cout << "num = " << num << endl;
return 0;
}
lexical_cast的声明如下,
template<typename Target, typename Source> Target lexical_cast(Source arg);
所以使用的时候特别简单,例如我们需要把Source转成Target, 只需要简单的这样写:
Target t = boost::lexical_cast<Target>(source); //source的类型是Source的
转换不成功的时候,lexical_cast会抛出一个bad_lexical_cast的异常,严谨的用法应该是:
Target t;
Source source;
//source应该有初始值
try {
t = boost::lexical_cast<Target>(source);
} catch (bad_lexical_cast& ex) {
//异常处理
}