首页IT科技boost 翻译(boost/lexical_cast.hpp的简单使用方法_学着站在巨人的肩膀上_百度空间)

boost 翻译(boost/lexical_cast.hpp的简单使用方法_学着站在巨人的肩膀上_百度空间)

时间2025-05-02 08:48:33分类IT科技浏览3301
导读:1、字符串->数值 C++代码 #include <boost/lexical_cast.hpp> #include <iostream>...

1            、字符串->数值

C++代码

#include <boost/lexical_cast.hpp> #include <iostream> int main() { using boost::lexical_cast; int a = lexical_cast<int>("123"); double b = lexical_cast<double>("123.12"); std::cout<<a<<std::endl std::cout<<b<<std::endl; return 0; }

#include <boost/lexical_cast.hpp>#include <iostream>int main(){ using boost::lexical_cast; int a = lexical_cast<int>("123"); double b = lexical_cast<double>("123.12"); std::cout<<a<<std::endl std::cout<<b<<std::endl; return 0;}

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 0; }

#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 0;}

3      、异常

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 1; } cout<<i<<endl; return 0; }

#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 1; } cout<<i<<endl; return 0;}

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

4         、注意事项

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

C++代码

int d = boost::lexical_cast<int>("123");

int d = boost::lexical_cast<int>("123");

相当于

C++代码

int d; std::stringstream s; s<<"123"; s>>d;

int d;std::stringstream s;s<<"123";s>>d;

5                 、小结

我们已经体验了boost::lexcial_cast      。当然         ,lexical_cast不仅仅局限于字符串类型与数值类型之间的转换:可在任意可输出到stringstream的类型和任意可从stringstream输入的类型间转换         。

;-)

声明:本站所有文章     ,如无特殊说明或标注                  ,均为本站原创发布                 。任何个人或组织            ,在未征得本站同意时  ,禁止复制         、盗用      、采集                 、发布本站内容到任何网站            、书籍等各类媒体平台         。如若本站内容侵犯了原著者的合法权益                 ,可联系我们进行处理      。

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
极致cms模板(极致CMS自动采集伪原创发布软件:强化网站SEO的不可或缺工具) 台湾能用的云盘(台湾云主机购买流程是什么)