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

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 介面互操作 |
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)"); // 成功
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);
#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