boost::lexical_cast

boost::lexical_cast 是 C++ 中最优雅的类型转换工具之一,尤其适合配置解析、CLI 参数处理、日志系统等场景。
// 字符串 转 数值
try {
    std::string str1 = "123";
    int n = boost::lexical_cast<int>(str1);
    std::cout << "String to int: " << n << std::endl;

    std::string str2 = "3.14159";
    double pi = boost::lexical_cast<double>(str2);
    std::cout << "String to double: " << pi << std::endl;

    std::string str3 = "true";
    bool flag = boost::lexical_cast<bool>(str3);  // 注意:默认不支持 "true"/"false"
    std::cout << "String to bool: " << std::boolalpha << flag << std::endl;

} catch (const boost::bad_lexical_cast& e) {
    std::cerr << "Conversion failed: " << e.what() << std::endl;
}
// 数值 转 字符串
int age = 25;
std::string s_age = boost::lexical_cast<std::string>(age);
std::cout << "int to string: " << s_age << std::endl;

double price = 99.99;
std::string s_price = boost::lexical_cast<std::string>(price);
std::cout << "double to string: " << s_price << std::endl;

bool is_ok = true;
std::string s_bool = boost::lexical_cast<std::string>(is_ok ? 1 : 0); // 输出 "1"
std::cout << "bool to string: " << s_bool << std::endl;
// 浮点数精度控制(⚠️ 注意!)
double d = 1.23456789;
std::string s = boost::lexical_cast<std::string>(d);
std::cout << "Double to string: " << s << std::endl; // 可能输出 "1.23457"
// 使用 std::ostringstream 手动控制精度。
#include <sstream>
#include <iomanip>

std::string to_string_precise(double d) {
    std::ostringstream oss;
    oss << std::setprecision(10) << std::fixed << d;
    return oss.str();
}
posted @ 2021-03-06 16:30  osbreak  阅读(137)  评论(0)    收藏  举报