zoukankan      html  css  js  c++  java
  • 4.6.2 万能转换器boost::lexical_cast

    4.6.2 万能转换器boost::lexical_cast - 51CTO.COM

    4.6.2 万能转换器boost::lexical_cast

    2009-07-08 11:51 白乔/左飞 电子工业出版社 我要评论(0) 字号:T | T
    一键收藏,随时查看,分享好友!

    《把脉VC++》第4章对象的赋值与转换,本章介绍了对象的初始化(从无到有)和赋值(从A到B)问题,讨论如何对对象进行类型上的、数值上的转换,并结合我们常常接触到的数学运算和字符编码问题展开讨论。本节讲述的是万能转换器boost::lexical_cast。

    AD:

    4.6.2  万能转换器boost::lexical_cast

    boost::lexical_cast为数值之间的转换(conversion)提供了一揽子方案,比如:将一个字符串"123"转换成整数123,代码如下:

    1. string s = "123";  
    2. int a = lexical_cast<int>(s); 

    这种方法非常简单,笔者强烈建议大家忘掉std诸多的函数,直接使用boost:: lexical_cast。如果转换发生了意外,lexical_cast会抛出一个bad_lexical_cast异常,因此程序中需要对其进行捕捉。

    现在动手

    编写如下程序,体验如何使用boost:: lexical_cast完成数值转换。

    【程序 4-11】使用boost:: lexical_cast完成对象数值转换

    1. 01  #include "stdafx.h" 
    2. 02    
    3. 03  #include <iostream>  
    4. 04  #include <boost/lexical_cast.hpp>  
    5. 05    
    6. 06  using namespace std;  
    7. 07  using namespace boost;  
    8. 08    
    9. 09  int main()  
    10. 10  {  
    11. 11      string s = "123";  
    12. 12      int a = lexical_cast<int>(s);  
    13. 13      double b = lexical_cast<double>(s);  
    14. 14    
    15. 15      printf("%d\r\n", a + 1);  
    16. 16      printf("%lf\r\n", b + 1);  
    17. 17    
    18. 18      try 
    19. 19      {  
    20. 20          int c = lexical_cast<int>("wrong number");  
    21. 21      }  
    22. 22      catch(bad_lexical_cast & e)  
    23. 23      {  
    24. 24          printf("%s\r\n", e.what());  
    25. 25      }  
    26. 26    
    27. 27      return 0;28 } 

    如上程序实现字符串"123"到整数、双精度实数的转换(为了防止程序作弊,我们特意让它将值加1),结果输出如图4-19所示。

  • 相关阅读:
    与众不同 windows phone (50)
    与众不同 windows phone (49)
    重新想象 Windows 8.1 Store Apps (93)
    重新想象 Windows 8.1 Store Apps 系列文章索引
    重新想象 Windows 8.1 Store Apps (92)
    重新想象 Windows 8.1 Store Apps (91)
    重新想象 Windows 8.1 Store Apps (90)
    重新想象 Windows 8.1 Store Apps (89)
    重新想象 Windows 8.1 Store Apps (88)
    重新想象 Windows 8.1 Store Apps (87)
  • 原文地址:https://www.cnblogs.com/lexus/p/2593659.html
Copyright © 2011-2022 走看看