改天記得把自己那個代碼中的改成這個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所示。

 

 
(點擊查看大圖)圖4-19  運行結果

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章