用boost::lexical_cast进行数值转换
来源:互联网 发布:我的世界 知乎 编辑:程序博客网 时间:2024/04/30 00:46
在STL库中,我们可以通过stringstream来实现字符串和数字间的转换:
int i = 0;
stringstream ss;
ss << "123";
ss >> i;
但stringstream是没有错误检查的功能,例如对如如下代码,会将i给赋值为12.
ss << "12.3";
ss >> i;
甚至连这样的代码都能正常运行:
ss << "hello world";
ss >> i;
这显然不是我们所想要看到的。为了解决这一问题,可以通过boost::lexical_cast来实现数值转换:
int i = boost::lexical_cast<int>("123");
double d = boost::lexical_cast<double>("12.3");
对于非法的转换,则会抛异常:
try
{
int i = boost::lexical_cast<int>("12.3");
}
catch (boost::bad_lexical_cast& e)
{
cout << e.what() << endl;
}
对于16机制数字的转换,可以以如下方式进行:
template <typename ElemT>
struct HexTo {
ElemT value;
operator ElemT() const {return value;}
friend std::istream& operator>>(std::istream& in, HexTo& out) {
in >> std::hex >> out.value;
return in;
}
};
int main(void)
{
int x = boost::lexical_cast<HexTo<int>>("0x10");
}
转载自:http://www.cnblogs.com/TianFang/archive/2013/02/05/2892506.html
- 用boost::lexical_cast进行数值转换
- 用boost::lexical_cast进行数值转换
- boost c++ lib on linux(2) - lexical_cast字符串数值转换
- boost之lexical_cast库,数值/字符串转换及其异常处理
- BOOST转换lexical_cast
- 用boost::lexical_cast用法解析
- Boost的转换函数numeric_cast和lexical_cast
- 实现 boost lexical_cast(基本类型转换)
- BOOST 类型转换(lexical_cast)崩溃问题
- BOOST库 之 lexical_cast类型转换
- Boost::lexical_cast
- Boost :Lexical_cast
- boost::lexical_cast
- boost lexical_cast
- boost::lexical_cast
- boost lexical_cast
- boost::lexical_cast
- BOOST-lexical_cast
- Unable to connect to Command Metric Stream.解决方案
- SPARK:sortByKey和sortBy 函数讲解
- Java设计模式——模板方法(Template Method)以及策略模式比较
- ST官网下载固件函数库————20170507
- ios 日期格式化
- 用boost::lexical_cast进行数值转换
- 有return的情况下try catch finally的执行顺序(最有说服力的总结)
- eclipse搭建maven之springmvc工程
- 论文笔记——CVPR 2017 Dilated Residual Networks
- JavaScript入门(二)
- 数据结构之红黑树
- Java 变量定义的时候注意事项
- Tarjan算法流程和简要证明
- Android/iOS拍照扫描自动识别银行卡号SDK