boost lexical_cast使用

       在进行编码时经常需要将整型数转化为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) {

    //异常处理

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值