c++資料類型萬能轉換器boost::lexical_cast .

來源:互聯網
上載者:User

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  運行結果

 

光碟片導讀

該項目對應於光碟片中的目錄"/ch04/LexicalCastTest"。

===============================

以上摘自《把脈VC++》第4.6.2小節的內容 ,轉載請註明出處。

如果你想與我交流,請點擊如下連結加我為好友:http://student.csdn.net/invite.php?u=113292&c=8913f87cffe7d533

 

from:http://blog.csdn.net/bluejoe2000/article/details/4461421

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.