[英]C++: stringstream parsing
我正在寻找一种简单,优雅的方法来用stringstream(或istringstream或其他Std-C ++类)解析数字(dec和hex)。
十进制数字(例如11)的有效输入应为11 0xb bh
通常,我会使用正则表达式,但由于缺少库和C ++编译器,此处无法使用正则表达式。
谢谢!
这可能很愚蠢,但是恕我直言,最简单的解决方案是std::stringstream
+ std::hex
(及其他 )
unsigned int x;
std::stringstream ss;
ss << std::hex << "0xb";
ss >> x;
我可能会丢失一些内容,但是我认为默认的istream::operator >>
无法从输入中自动检测到碱基。 操纵器std::hex
只能用于将基数强制为16,但是它将应用于所有输入,而无需考虑前缀“ 0x”或后缀“ h”。
我们可以通过为自定义类型重载operator >>
来解决,并调用std::stoi()
:
struct ParsedInt
{
int val;
};
inline std::istream& operator>>( std::istream& strm, ParsedInt& i )
{
std::string s; strm >> s;
i.val = 0;
if( ! s.empty() )
{
if( s.back() == 'h' )
// explicitly use base 16 to parse hex
i.val = static_cast<int>( std::stoul( s, nullptr, 16 ) );
else
// stoi() with base 0 will detect prefix "0x".
i.val = static_cast<int>( std::stoul( s, nullptr, 0 ) );
}
return strm;
}
用法示例:
int main()
{
std::stringstream ss( "11 0xb bh -11 0xffffffff fffffffeh" );
ParsedInt i;
while( ss >> i )
{
std::cout << i.val << "\n";
}
}
输出:
11
11
11
-11
-1
-2
现场演示 。
编辑:
原始代码因std::out_of_range
异常(如0xFFFFFFFF
十六进制负数)而崩溃,已通过将std::stoi()
替换为std::stoul()
并通过static_cast
将结果存储到int
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.