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

萬能轉換器 boost::lexical_cast 詳解:型別安全的字串與數值互轉

     編輯:關於C語言

前言

C++ 標準庫提供 std::stoi、std::to_string、stringstream 等轉換工具,但介面分散、異常處理不一。boost::lexical_cast 以單一模板函式統一所有「可流式輸入/輸出」型別間的轉換,且提供一致的異常語意,是現代 C++ 專案的首選轉換工具。

一、 核心用法:一行搞定

#include <boost/lexical_cast.hpp>
#include <string>

std::string s = "123";
int a = boost::lexical_cast<int>(s);       // "123" → 123
double b = boost::lexical_cast<double>(s); // "123" → 123.0

std::cout << a + 1 << std::endl; // 124
std::cout << b + 1 << std::endl; // 124.0

二、 完整實戰程式碼

#include "stdafx.h"
#include <iostream>
#include <boost/lexical_cast.hpp>

using namespace std;
using namespace boost;

int main() {
    string s = "123";
    int a = lexical_cast<int>(s);
    double b = lexical_cast<double>(s);

    printf("%d\r\n", a + 1);
    printf("%lf\r\n", b + 1);

    // 異常處理示範
    try {
        int c = lexical_cast<int>("wrong number");
    }
    catch (bad_lexical_cast& e) {
        printf("Conversion failed: %s\r\n", e.what());
    }

    return 0;
}

三、 執行結果

124
124.000000
Conversion failed: bad lexical cast: source type value could not be interpreted as target

lexical_cast 執行結果

四、 支援的型別範圍

  • 所有支援 operator<< (輸出) 與 operator>> (輸入) 的型別
  • 內建型別:int, double, bool, long, unsigned...
  • 標準庫:std::string, std::wstring, std::complex...
  • 使用者定義型別:只需實作流式運算子

五、 錯誤處理機制

  • 轉換失敗拋出 boost::bad_lexical_cast(繼承自 std::bad_cast)
  • e.what() 回傳具體錯誤描述
  • **必須捕獲處理**,否則導致程式終止

六、 與標準庫方案對比

方案優點缺點適用場景
boost::lexical_cast介面統一、型別安全、異常語意一致、支援擴充較慢(內部用 stringstream)、需 Boost 依賴一般應用、型別多樣、重視可維護性
std::stoi/stod/to_string (C++11)零依賴、效能較好介面分散、錯誤碼/異常混用、不支援自訂型別高效能、僅轉內建型別、無 Boost 環境
stringstream標準庫、靈活語法冗長、需手動檢狀態位複雜格式化、舊標準專案
atoi/strtod/sprintf極快、C 相容不安全、無型別檢查、行為未定義風險極度效能敏感、C 介面互操作

七、 進階技巧

1. 自訂型別支援

struct Point { int x, y; };
std::ostream& operator<<(std::ostream& os, const Point& p) {
    return os << '(' << p.x << ',' << p.y << ')';
}
std::istream& operator>>(std::istream& is, Point& p) {
    char c; return is >> c >> p.x >> c >> p.y >> c; // 解析 (x,y)
}

Point p = lexical_cast<Point>("(10,20)"); // 成功

2. 預設值模式(避免異常)

template <typename Target, typename Source>
Target lexical_cast_or_default(const Source& src, const Target& def) {
    try { return lexical_cast<Target>(src); }
    catch (bad_lexical_cast&) { return def; }
}

int port = lexical_cast_or_default(config["port"], 8080);

八、 總結

  • 首選工具:現代 C++ 專案中型別轉換的標準答案
  • 記住三步驟:#include <boost/lexical_cast.hpp> → using namespace boost; → lexical_cast<Target>(source)
  • 必捕異常:catch (bad_lexical_cast&)
  • 效能敏感場景:可考慮 std::from_chars (C++17) 或專用快速解析器

本文出自 “白喬博客” 博客,請務必保留此出處 https://bluejoe.blog.51cto.com/807902/193411

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