首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

實戰 Boost (二):驗證環境配置的 Hello World 程序

     編輯:關於C++

前置條件

請先完成《實戰 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、 等核心組件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved