参考原著地址:http://einverne.github.io/post/2015/12/boost-learning-note-1.html
转换对象要求
lexical_cast 对转换对象有如下要求:
- 转换起点对象是可流输出的,即定义了 operator«
- 转换终点对象是可流输入的,即定义了 operator»
- 转换终点对象必须是可缺省构造和可拷贝构造的
C++中内建类型(int,double等)和std::string 都是符合三个条件的。
1 #include <boost/lexical_cast.hpp> 2 using namespace boost; 3 #include <iostream> 4 using namespace std; 5 using boost::lexical_cast; 6 7 int main() 8 { 9 //lexical_cast在转换字符串时,字符串中只能包含数字和小数点,不能出现除e/E以外的英文字符或者其他非数字字符。 10 int a = lexical_cast<int>("123"); 11 long b = lexical_cast<long>("2015"); 12 double c = lexical_cast<double>("123.12"); 13 14 cout<< a << b << c <<endl; 15 16 //数字转换成字符串时不支持高级格式控制 17 string str = lexical_cast<string>(1234); 18 cout<<str<<endl; 19 20 cout<<lexical_cast<string>(1.23)<<endl; 21 cout<<lexical_cast<string>(0x11)<<endl; 22 23 //try catch 24 //当 lexical_cast 无法执行转换时会抛出异常 bad_lexical_cast ,它是 std::bad_cast 的派生类。可以使用 try/catch 块来保护代码 25 try 26 { 27 cout<<lexical_cast<int>("0x100"); 28 cout<<lexical_cast<bool>("false"); 29 } 30 catch(bad_lexical_cast& e) 31 { 32 cout<<"error:"<<e.what()<<endl; 33 } 34 char i = getchar(); 35 return 0; 36 }
作者:长风
Email:844064492@qq.com
QQ群:607717453
Git:https://github.com/zhaohu19910409Dz
开源项目:https://github.com/OriginMEK/MEK
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
感谢您的阅读。如果觉得有用的就请各位大神高抬贵手“推荐一下”吧!你的精神支持是博主强大的写作动力。
如果觉得我的博客有意思,欢迎点击首页左上角的“+加关注”按钮关注我!