boost::lexical_cast為數值之間的轉換(conversion)提供了一攬子方案,比如:將一個字符串"123"轉換成整數123,代碼如下:
- string s = "123";
- int a = lexical_cast<int>(s);
這種方法非常簡單,筆者強烈建議大家忘掉std諸多的函數,直接使用boost:: lexical_cast。如果轉換發生了意外,lexical_cast會拋出一個bad_lexical_cast異常,因此程序中需要對其進行捕捉。
現在動手
編寫如下程序,體驗如何使用boost:: lexical_cast完成數值轉換。
【程序 4-11】使用boost:: lexical_cast完成對象數值轉換
- 01 #include "stdafx.h"
- 02
- 03 #include <iostream>
- 04 #include <boost/lexical_cast.hpp>
- 05
- 06 using namespace std;
- 07 using namespace boost;
- 08
- 09 int main()
- 10 {
- 11 string s = "123";
- 12 int a = lexical_cast<int>(s);
- 13 double b = lexical_cast<double>(s);
- 14
- 15 printf("%d/r/n", a + 1);
- 16 printf("%lf/r/n", b + 1);
- 17
- 18 try
- 19 {
- 20 int c = lexical_cast<int>("wrong number");
- 21 }
- 22 catch(bad_lexical_cast & e)
- 23 {
- 24 printf("%s/r/n", e.what());
- 25 }
- 26
- 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