boost/lexical_cast.hpp的简单使用方法

  1. #include <boost/lexical_cast.hpp>  
  2. #include <string>  
  3. #include <iostream>   
  4. int main()   
  5. {   
  6.         using std::string;
  7.         using std::cout;   
  8.         using std::endl;
  9.   
  10.         int i;   
  11.         try  
  12.          {   
  13.              i = boost::lexical_cast<int>("xyz");
  14.          
  15.              const double d = 123.12;   
  16.              string s = boost::lexical_cast<string>(d);   
  17.              cout<<s<<std::endl;   
  18.          }   
  19.         catch(boost::bad_lexical_cast& e)   
  20.          {   
  21.              cout<<e.what()<<endl;   
  22.             return 1;   
  23.          }   
  24.          cout<<i<<endl;   
  25.         return 0;   
  26. }  

 

显然“xyz”并不能转换为一个int类型的数值,于是抛出异常,捕捉后输出“bad lexical cast: source type value could not be interpreted as target”这样的信息。

 

4、注意事项

 

lexical_cast依赖于字符流std::stringstream,其原理相当简单:把源类型读入到字符流中,再写到目标类型中,就大功告成。

 

5、小结

 

我们已经体验了boost::lexcial_cast。当然,lexical_cast不仅仅局限于字符串类型与数值类型之间的转换:可在任意可输出到stringstream的类型和任意可从stringstream输入的类型间转换。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值