Boost的万能转换器-->lexical_cast
来源:互联网 发布:360彩票11选5遗漏数据 编辑:程序博客网 时间:2024/05/16 05:50
boost::lexical_cast为数值之间的转换(conversion)提供了一揽子方案,比如:将一个字符串"123"转换成整数123,代码如下:
- string s = "123";
- int a = lexical_cast<int>(s);
这种方法非常简单,笔者强烈建议大家忘掉std诸多的函数,直接使用boost:: lexical_cast。如果转换发生了意外,lexical_cast会抛出一个bad_lexical_cast异常,因此程序中需要对其进行捕捉。
现在动手
现在动手
编写如下程序,体验如何使用boost:: lexical_cast完成数值转换。
【程序 4-11】使用boost:: lexical_cast完成对象数值转换
- 01 #include "stdafx.h"
- 02
- 03 #include <iostream>
- 04 #include <boost/lexical_cast.hpp>
- 05
- 06 using namespace std;
- 07 using namespace boost;
- 08
- 09 int main()
- 10 {
- 11 string s = "123";
- 12 int a = lexical_cast<int>(s);
- 13 double b = lexical_cast<double>(s);
- 14
- 15 printf("%d\r\n", a + 1);
- 16 printf("%lf\r\n", b + 1);
- 17
- 18 try
- 19 {
- 20 int c = lexical_cast<int>("wrong number");
- 21 }
- 22 catch(bad_lexical_cast & e)
- 23 {
- 24 printf("%s\r\n", e.what());
- 25 }
- 26
- 27 return 0;28 }
如上程序实现字符串"123"到整数、双精度实数的转换(为了防止程序作弊,我们特意让它将值加1),结果输出如图4-19所示。
(点击查看大图)图4-19 运行结果
0 0
- Boost的万能转换器-->lexical_cast
- 万能转换器boost::lexical_cast
- 万能转换器boost::lexical_cast
- 万能转换器boost::lexical_cast
- 4.6.2 万能转换器boost::lexical_cast
- c++数据类型万能转换器boost::lexical_cast
- boost::lexical_cast 的使用
- Boost::Lexical_cast 的使用
- Boost::Lexical_Cast的使用
- 【转载】boost::lexical_cast 的使用
- boost::lexical_cast库的使用
- boost::lexical_cast常见用法详解之万能转换
- 【Boost】基于boost::lexical_cast的to_string函数
- Boost::lexical_cast
- Boost :Lexical_cast
- boost::lexical_cast
- boost lexical_cast
- boost::lexical_cast
- 秒杀一切的CSS hack
- php 生成GUID
- JSONP跨域原理和用法
- 模板方法模式Template method(类行为型)
- imfilter 的用法
- Boost的万能转换器-->lexical_cast
- Introduction to Core Bluetooth: Building a Heart Rate Monitor
- vertica安装注意事项
- js与java相互aes加密解密
- ios设备型号列表
- 多线程的使用:优缺点
- [无线] 浅析当代 LBS 技术
- c# 类、枚举的定义与使用
- servlet中web.xml配置详解