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

Art*_*hur 5 c++ boost lexical-cast

我在本主题中看到C++ 将十六进制字符串转换为有符号整数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;
}
Run Code Online (Sandbox Code Playgroud)

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

boost 不支持这种从 string hex 到 int 的转换?

小智 2

根据C++ 将十六进制字符串转换为有符号整数的答案:

看来,sincelexical_cast<>被定义为具有流转换语义。遗憾的是,流不理解“0x”符号。所以boost::lexical_cast我的手卷和我的手卷都不能很好地处理六角弦。

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

函数lexical_cast模板提供了一种方便且一致的形式,用于支持以文本形式表示的任意类型之间的常见转换。它提供的简化是在表达式级别上为此类转换提供便利。对于涉及更多的转换,例如精度或格式需要比 的默认行为提供的更严格的控制,建议使用lexical_cast传统方法。std::stringstream

因此,对于更多涉及的转换,std::stringstream建议使用。

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

stoi原型是:

int stoi( const std::string& str, std::size_t* pos = nullptr, int base = 10 );
Run Code Online (Sandbox Code Playgroud)

您的程序可以转换为

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

输出将是

1000
Run Code Online (Sandbox Code Playgroud)