我在这个话题中看到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 theboost::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 oflexical_cast
, the conventionalstd::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/