Boost初试:lexical_cast

虽然早就听过Boost,也早就已经下了一个收藏了,可一直没有用,呵呵,这回有时间了,可以好好学习一下了
原来以为是必须要编译成lib才行,所以一直都是找编译的方法,终于在stlchina上找到一篇文章,也是boost入门的,说是不编译也能用,只有python,regex才用编译,打开src一看,都是templete,看来只要include就能用。
这样,解压了,只有100M,可如果都编译了,会占1G,不过,删了obj ,会少一半。暂时还不学python和c++和连接编程。而且还在学Lua,可能,python会暂时休息一会吧。

不费话了,设置了include directory后,写了一个最简单的:lexical_cast<>(),用来实现string和数据之间的转换。类似C库中的atoi()之类的函数。

#pragma warning (disable:4819)

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

int main(int argc, char *argv[])
{
        using boost::lexical_cast;

        int num=lexical_cast<int>("123");
 
       double num2=lexical_cast<double>("123.12");
 
       std::string str=lexical_cast<std::string>(12345);

        std::cout<<num<<std::endl;
        std::cout<<num2<<std::endl;
        std::cout<<str<<std::endl;
 
       return 0;
}

作为一个有工业级强度的库,当然对错误的处理是少不了的,如果转换错误,则会抛出一个异常:boost::bad_lexical_cast

看这个代码:

#pragma warning (disable:4819)

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

int main(int argc, char *argv[])
{
 int num=0;
 
 try
 {
  //bad lexical cast: source type value could not be interpreted as target
  num=lexical_cast<int>("abcd");
 }
 catch (boost::bad_lexical_cast& e)
{
  std::cout<<e.what()<<std::endl;
  return 1;
 }
 return 0;
}

最后,小说一下原理,其实lexical_cast就是对stringstream的一个封装,用一个stringstream做中介,实现转换。

OK,第一课过去了。明天要下一课!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值