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,其原理相当简单:把源类型读入到字符流中,再写到目标类型中,就大功告成。

最新文章

  1. MonogDB初探增加和删除
  2. python 调用nmap
  3. 编译android源码官方教程(6)编译内核
  4. Kali Linux Web 渗透测试视频教程—第十四课-arp欺骗、嗅探、dns欺骗、session劫持
  5. COJ976 WZJ的数据结构(负二十四)
  6. 产生冠军 map 的 应用 .
  7. 【Shell脚本学习14】Shell echo命令
  8. Python在Windows下开发环境配置汇总
  9. CodeForces 554B(扫房间)
  10. 高效算法——Bin Packing F - 贪心
  11. 获得HttpServletResponse及其他对象
  12. poj 3104 Drying(二分搜索之最大化最小值)
  13. 爱加密亮相第十八届软博会,移动App安全引关注
  14. POJ 3076 Sudoku DLX精确覆盖
  15. Android为TV端助力 使用shared注意事项
  16. 将连接数据库的JDBC提成BaseDao
  17. 在ASP.NET Core MVC中子类Controller拦截器要先于父类Controller拦截器执行
  18. Day 5-5 绑定方法与非绑定方法
  19. Spark2.3(四十):如何使用java通过yarn api调度spark app,并根据appId监控任务,关闭任务,获取任务日志
  20. log4j 文件配置

热门文章

  1. Linux 利用busybox制作根文件系统
  2. 解决asp.net上传文件时文件太大导致的错误
  3. js点击按钮触发事件的方法
  4. appium+python自动化31-android_uiautomator定位
  5. offset()和position()
  6. linux c下,从路径名中分离文件名
  7. 修改win7远程桌面端口号
  8. 脱壳系列(二) - EZIP 壳
  9. DOM笔录
  10. python开发_python中字符串string操作