c++ - boost::lexical_cast 可以将字符串中的十六进制转换为整数吗?

标签 c++ boost lexical-cast

我在这个话题中看到C++ convert hex string to signed integer boost::lexical_cast 可以将字符串中的十六进制转换为另一种类型(int、long...)

但是当我尝试这段代码时:

std::string s = "0x3e8";

try {
    auto i = boost::lexical_cast<int>(s);
    std::cout << i << std::endl;        // 1000
}
catch (boost::bad_lexical_cast& e) {
    // bad input - handle exception
    std::cout << "bad" << std::endl;
}

它以一个错误的词法转换异常结束!

boost 不支持这种从字符串 hex 到 int 的转换?

最佳答案

根据 C++ convert hex string to signed integer 的回答:

It appears that since lexical_cast<> is defined to have stream conversion semantics. Sadly, streams don't understand the "0x" notation. So both the boost::lexical_cast and my hand rolled one don't deal well with hex strings.

此外,根据 boost::lexical_cast<>文档

The lexical_cast function template offers a convenient and consistent form for supporting common conversions to and from arbitrary types when they are represented as text. The simplification it offers is in expression-level convenience for such conversions. For more involved conversions, such as where precision or formatting need tighter control than is offered by the default behavior of lexical_cast, the conventional std::stringstream approach is recommended.

因此,对于更复杂的转换,std::stringstream推荐。

如果您可以访问 C++11 编译器,则可以使用 std::stoi将任何十六进制字符串转换为整数值。

stoi原型(prototype)是:

int stoi( const std::string& str, std::size_t* pos = nullptr, int base = 10 );

你的程序可以转换成

int main() {
    std::string s = "3e8";
    auto i = std::stoi(s, nullptr, 16);
    std::cout << i << '\n';
}

输出将是

1000

关于c++ - boost::lexical_cast 可以将字符串中的十六进制转换为整数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74302381/

相关文章:

c++ - lexical_cast int 到字符串

c++ - 如何使用 boost::lexical_cast 和 std::boolalpha?即 boost::lexical_cast< bool > ("true")

c++ - 哪些选项(如果有)在 Visual Studio 2015 中暗示/CLR

C++:并发和析构函数

gcc - boost::program_options 给出 malloc 错误

c++ - 从任何类型转换

c++ - boost::lexical_cast<signed char> 无法处理负数?

c++ - 未定义引用

c++ - setw() 在我的代码上无法正常工作

python - 如何使用 boost.python 提取 unicode 字符串