首页 > 其他 > 详细

Boost::lexical_cast类型转换

时间:2015-09-10 19:04:24      阅读:218      评论:0      收藏:0      [点我收藏+]

1、字符串->数值

C++代码

 1 #include <boost/lexical_cast.hpp> 
 2 #include <iostream> 
 3 int main() 
 4 { 
 5     using boost::lexical_cast; 
 6     int a = lexical_cast<int>("123"); 
 7     double b = lexical_cast<double>("123.12"); 
 8     std::cout<<a<<std::endl 
 9     std::cout<<b<<std::endl; 
10     return 0; 
11 }

2、数值->字符串

C++代码

 1 #include <boost/lexical_cast.hpp> 
 2 #include <string> 
 3 #include <iostream> 
 4 int main() 
 5 { 
 6     using std::string; 
 7     const double d = 123.12; 
 8     string s = boost::lexical_cast<string>(d); 
 9     std::cout<<s<<std::endl; 
10     return 0; 
11 }

3、异常

  如果转换发生了意外,lexical_cast会抛出一个bad_lexical_cast异常,因此程序中需要对其进行捕捉。

C++代码

 1 #include <boost/lexical_cast.hpp> 
 2 #include <iostream> 
 3 int main() 
 4 { 
 5     using std::cout; 
 6     using std::endl; 
 7     int i; 
 8     try 
 9     { 
10         i = boost::lexical_cast<int>("xyz"); 
11     } 
12     catch(boost::bad_lexical_cast& e) 
13     { 
14         cout<<e.what()<<endl; 
15         return 1; 
16     } 
17     cout<<i<<endl; 
18     return 0; 
19 } 

  显然“xyz”并不能转换为一个int类型的数值,于是抛出异常,捕捉后输出“bad lexical cast: source type value could not be interpreted as target”这样的信息。

4、注意事项

  lexical_cast依赖于字符流std::stringstream,其原理相当简单:把源类型读入到字符流中,再写到目标类型中,就大功告成。

Boost::lexical_cast类型转换

原文:http://www.cnblogs.com/blueoverflow/p/4798681.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!