laxical_cast使用
发布日期:2021-10-10 05:31:24 浏览次数:20 分类:技术文章

本文共 1370 字,大约阅读时间需要 4 分钟。

lexical_cast 使用

文章目录

引言

使用条件:适合下面的1.2种。其他的情况会抛异常。

  1. 字符串 到 数值类型的转换
  2. 数值 到 字符串的转换
  3. 异常处理情况

代码

#include 
#include
#include
using boost::lexical_cast;int boost_a2i(){ int a = boost::lexical_cast
("123456"); std::cout << a << std::endl; double b = boost::lexical_cast
("123.12"); std::cout << b << std::endl; long double c = lexical_cast
("123.11"); std::cout << c << std::endl; return 0;}int boost_i2a(){ using std::string; const double d = 123.12; string s = boost::lexical_cast
(d); std::cout << s << std::endl; return 0;}int boost_except(){ int i; try{ i = boost::lexical_cast
("abc"); } catch(boost::bad_lexical_cast & e) { std::cout << e.what() << std::endl; return 1; } std::cout << i << std::endl; return 0;}int boost_except2(){ int i; i = boost::lexical_cast
("abc"); std::cout << "except happen!" << std::endl; return 0;}int main(int argc, char ** argv){ if (argc != 2) { std::cout << "less params" << std::endl; return -1; } int index = atoi(argv[1]); switch(index) { case 0: boost_a2i(); break; case 1: boost_i2a(); break; case 2: boost_except(); break; case 3: try { boost_except2(); } catch (const std::exception &exc) { std::cout << "catch it!" << std::endl; std::cout << exc.what() << std::endl; } break; default: std::cout << "default" << std::endl; break; } return 0;}

转载地址:https://blog.csdn.net/qq_22054285/article/details/87100373 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:linux下so编写 - 动态库-类
下一篇:Boost智能指针——shared_ptr

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2024年03月23日 08时33分57秒