这篇文章介绍了C++使用boost::lexical_cast进行数值转换的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
在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");
}到此这篇关于C++使用boost::lexical_cast进行数值转换的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持编程学习网。
织梦狗教程
本文标题为:C++使用boost::lexical_cast进行数值转换
基础教程推荐
猜你喜欢
- C++实现ETW进行进程变动监控详解 2023-05-15
- C语言编程C++旋转字符操作串示例详解 2022-11-20
- C语言实现宾馆管理系统课程设计 2023-03-13
- C++实战之二进制数据处理与封装 2023-05-29
- 全面了解C语言 static 关键字 2023-03-26
- centos 7 vscode cmake 编译c++工程 2023-09-17
- [c语言-函数]不定量参数 2023-09-08
- 带你深度走入C语言取整以及4种函数 2022-09-17
- [C语言]二叉搜索树 2023-09-07
- C语言 详解字符串基础 2023-03-27
