Boost组件 lexical_cast
来源:互联网 发布:ubuntu vi命令方向键 编辑:程序博客网 时间:2024/06/05 16:01
1.字符串转换为数值
#include <iostream>#include <boost/lexical_cast.hpp>int main(int argc, _TCHAR* argv[]){using boost::lexical_cast;int a = lexical_cast<int>("123");double b = lexical_cast<double>("1234.12");std::cout << a << std::endl;std::cout << b << std::endl;getchar();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.异常
如果转换失败,则会有异常bad_lexical_cast抛出。该异常类是标准异常类bad_cast的子类。
#include<boost/lexical_cast.hpp>#include <iostream>int main(){using std::cout;using std::endl;int i;try{i = boost::lexical_cast<int>("abcd");}catch(boost::bad_lexical_cast&e){cout<<e.what()<<endl;return1;}cout<<i<<endl;return0;}
显然“ abcd”并不能转换为一个int类型的数值,于是抛出异常,捕捉后输出“ badlexicalcast:source type value could not be interpreted as target”这样的信息。
4.注意事项
lexical_cast依赖于字符流std::stringstream,其原理相当简单:把源类型读入到字符流中,再写到目标类型中,就大功告成。
阅读全文
0 0
- 编程:Boost组件lexical_cast
- Boost组件lexical_cast
- Boost组件lexical_cast
- Boost 组件 lexical_cast
- Boost组件 lexical_cast
- Boost::lexical_cast
- Boost :Lexical_cast
- boost::lexical_cast
- boost lexical_cast
- boost::lexical_cast
- boost lexical_cast
- boost::lexical_cast
- BOOST-lexical_cast
- boost翻译(1):lexical_cast
- 学习boost之lexical_cast
- 万能转换器boost::lexical_cast
- 万能转换器boost::lexical_cast
- boost lexical_cast使用
- ORA-01034:ORACLE not available ORA-27101:shared memory realm does not exist
- Navicat11全系列激活(注册机)
- Javascript
- Pandas Merge后出现大量NaN值
- 深入java集合系列之Hashtable
- Boost组件 lexical_cast
- AI人工智能-Python实现人机对话
- JAVA ResourceBundle 加载包外配置文件
- python pep8编码规范 刚进it公司的伙伴注意
- BootStrap模态框使用
- Spring Cloud Config 的坑:以ssh方式从自己搭建的 git repository 取配置文件
- LED 闪烁代码
- HOJ 3274 插排次数
- 超完整的CHROME调试