我在本主题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;
}
它以一个糟糕的词汇转换异常结束!
boost不支持从字符串十六进制到int的这种类型的转换?
发布于 2022-11-03 12:44:38
根据C++将十六进制字符串转换为有符号整数的回答
似乎是因为
lexical_cast<>
被定义为具有流转换语义。不幸的是,流不懂"0x“符号。所以,boost::lexical_cast
和我的手都滚了,一个不能很好地处理十六进制字符串。
此外,根据boost::lexical_cast<>
文档
lexical_cast
函数模板提供了一种方便和一致的形式,用于支持以文本形式表示的与任意类型之间的通用转换。它所提供的简化是在表达级的方便,这样的转换。对于更多涉及到的转换,例如需要更严格控制精度或格式的地方,lexical_cast
**,std::stringstream
的默认行为推荐使用传统的**方法。
因此,对于更多涉及的转换,建议使用std::stringstream
。
如果您可以访问C++11编译器,则可以使用std::stoi
将任何十六进制sting转换为整数值。
stoi
原型是:
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
发布于 2022-11-03 15:35:19
您想要的东西存在于升压转换中
Boost.Convert建立在boost::lexical_cast经验的基础上,并进一步采用了与类型转换/转换相关的想法。
简单使用
例如,您可以使用流转换:
boost::cnv::cstream converter;
你可以用你想要的机械手来配置它,例如:
converter(std::hex)(std::skipws); // IO manipulators
您可以直接使用:
boost::optional<int> i;
converter(s, i);
std::cout << i << std::endl; // 1000
但我建议应用预先配置的错误处理:
auto f = apply<int>(std::ref(converter))
.value_or(-1); // decorate error-handling
现在您可以简单地写:
for (auto s : cases)
std::cout << f(s) << std::endl;
现场演示
#include <boost/convert.hpp>
#include <boost/convert/stream.hpp>
#include <iostream>
static const std::string cases[]{
"0x3e8", "3e8", "-7a", "-0x7a",
"0x-7a", // error
};
int main() {
boost::cnv::cstream converter;
converter(std::hex)(std::skipws); // IO manipulators
auto f = apply<int>(std::ref(converter)).value_or(-1); // decorate error-handling
for (auto s : cases)
std::cout << std::quoted(s) << " -> " << f(s) << std::endl;
auto g = apply<int>(std::ref(converter)); // throwing
for (auto s : cases)
try {
std::cout << std::quoted(s) << " -> " << g(s) << std::endl;
} catch (std::exception const& e) {
std::cout << e.what() << std::endl;
}
}
打印
"0x3e8" -> 1000
"3e8" -> 1000
"-7a" -> -122
"-0x7a" -> -122
"0x-7a" -> -1
"0x3e8" -> 1000
"3e8" -> 1000
"-7a" -> -122
"-0x7a" -> -122
"0x-7a" -> Attempted to access the value of an uninitialized optional object.
https://stackoverflow.com/questions/74302381
复制相似问题