Boost::lexical_cast类型转换
2024-08-22 07:47:52
1、字符串->数值
C++代码
#include <boost/lexical_cast.hpp>
#include <iostream>
int main()
{
using boost::lexical_cast;
int a = lexical_cast<int>("");
double b = lexical_cast<double>("123.12");
std::cout<<a<<std::endl
std::cout<<b<<std::endl;
return ;
}
2、数值->字符串
C++代码
#include <boost/lexical_cast.hpp>
#include <string>
#include <iostream>
int main()
{
using std::string;
const double d = 123.12;
string s = boost::lexical_cast<string>(d);
std::cout<<s<<std::endl;
return ;
}
3、异常
如果转换发生了意外,lexical_cast会抛出一个bad_lexical_cast异常,因此程序中需要对其进行捕捉。
C++代码
#include <boost/lexical_cast.hpp>
#include <iostream>
int main()
{
using std::cout;
using std::endl;
int i;
try
{
i = boost::lexical_cast<int>("xyz");
}
catch(boost::bad_lexical_cast& e)
{
cout<<e.what()<<endl;
return ;
}
cout<<i<<endl;
return ;
}
显然“xyz”并不能转换为一个int类型的数值,于是抛出异常,捕捉后输出“bad lexical cast: source type value could not be interpreted as target”这样的信息。
4、注意事项
lexical_cast依赖于字符流std::stringstream,其原理相当简单:把源类型读入到字符流中,再写到目标类型中,就大功告成。
最新文章
- MonogDB初探增加和删除
- python 调用nmap
- 编译android源码官方教程(6)编译内核
- Kali Linux Web 渗透测试视频教程—第十四课-arp欺骗、嗅探、dns欺骗、session劫持
- COJ976 WZJ的数据结构(负二十四)
- 产生冠军 map 的 应用 .
- 【Shell脚本学习14】Shell echo命令
- Python在Windows下开发环境配置汇总
- CodeForces 554B(扫房间)
- 高效算法——Bin Packing F - 贪心
- 获得HttpServletResponse及其他对象
- poj 3104 Drying(二分搜索之最大化最小值)
- 爱加密亮相第十八届软博会,移动App安全引关注
- POJ 3076 Sudoku DLX精确覆盖
- Android为TV端助力 使用shared注意事项
- 将连接数据库的JDBC提成BaseDao
- 在ASP.NET Core MVC中子类Controller拦截器要先于父类Controller拦截器执行
- Day 5-5 绑定方法与非绑定方法
- Spark2.3(四十):如何使用java通过yarn api调度spark app,并根据appId监控任务,关闭任务,获取任务日志
- log4j 文件配置