請先完成《實戰 Boost (一):配置 VS2008 開發環境》中的編譯與目錄設置。
boost::lexical_cast 類型轉換#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>
using namespace std;
int main() {
using boost::lexical_cast;
// 字符串 -> 數值
int a = lexical_cast<int>("123");
double b = lexical_cast<double>("123.0123456789");
// 數值 -> 字符串
string s0 = lexical_cast<string>(a);
string s1 = lexical_cast<string>(b);
cout << "number: " << a << " " << b << endl;
cout << "string: " << s0 << " " << s1 << endl;
// 異常處理:轉換失敗拋出 bad_lexical_cast
int c = 0;
try {
c = lexical_cast<int>("abcd");
} catch (boost::bad_lexical_cast& e) {
cout << e.what() << endl; // 輸出錯誤信息
}
return 0;
}
number: 123 123.0123456789
string: 123 123.0123456789
bad lexical cast: source type value could not be interpreted as target
lexical_cast 內部基於 stringstream 實現,支持任意可流式輸入/輸出類型間的雙向轉換boost::bad_lexical_cast(繼承自 std::bad_cast),必須捕獲處理<boost/lexical_cast.hpp> 即可使用,屬僅頭文件庫,無需鏈接額外 .lib若程序正常編譯運行並輸出上述結果,恭喜——Boost 環境已就緒,可進一步探索 thread、asio、