boost::lexical_cast 的使用
来源:互联网 发布:sql2000数据库无项目 编辑:程序博客网 时间:2024/05/17 04:54
1,字符串 到 数值类型的转换
2,数值 到 字符串的转换
3,异常处理情况
4,boost::lexical_cast 的原型:
template<typename Target, typename Source>
Target lexical_cast(Source arg);
lexical_cast 是依赖于字符串流 std::stringstream 的,其原理也是相当的简单:把源类型 (Source) 读入到字符流中,再写到目标类型 (Target) 中。但这里同时也带来了一些限制:
- 输入数据 (arg) 必须能够 “完整” 地转换,否则就会抛出 bad_lexical_cast 异常。例如:
int i = boost::lexical_cast<int>("123.456"); // this will throw
因为 “123.456” 只能 “部分” 地转换为 123,不能 “完整” 地转换为 123.456,还是让我们需要适当的注意一些这两个模板参数就好了。
- 由于 Visual C++ 6 的本地化(locale)部分实现有问题,如果使用了非默认的 locale,可能会莫名其妙地抛出异常。
- 源类型 (Source) 必须是一个可以输出到输出流的类型(OutputStreamable),也意味着该类型需要 operator<< 被定义。
- 同样的,目标类型 (Target) 必须是一个可以输入到输入流的类型 (InputStreamable),也意味着该类型需要 operator>> 被定义。
- 另外,Both Source and Target are CopyConstructible。
- Target is DefaultConstructible。
其中,下面的四个限制是在使用自定义类型之间转换时必须做的一些工作的(当然流行的使用的 C 库函数等等都是不可以处理自定义类型之间的转换的)。
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>
#define ERROR_LEXICAL_CAST 1
int main()
{
using boost::lexical_cast;
int a = 0;
double b = 0.0;
std::string s = "";
int e = 0;
try
{
// ----- 字符串 --> 数值
a = lexical_cast<int>("123");
b = lexical_cast<double>("123.12");
// ----- 数值 --> 字符串
s = lexical_cast<std::string>("123456.7");
// ----- 异常处理演示
e = lexical_cast<int>("abc");
}
catch(boost::bad_lexical_cast& e)
{
// bad lexical cast: source type value could not be interpreted as target
std::cout << e.what() << std::endl;
return ERROR_LEXICAL_CAST;
}
std::cout << a << std::endl; // 输出:123
std::cout << b << std::endl; // 输出:123.12
std::cout << s << std::endl; // 输出:123456.7
return 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】基于boost::lexical_cast的to_string函数
- Boost::lexical_cast
- Boost :Lexical_cast
- boost::lexical_cast
- boost lexical_cast
- boost::lexical_cast
- boost lexical_cast
- boost::lexical_cast
- BOOST-lexical_cast
- 什么是SCI
- http头状态信息意议以及在php使用header设置方法
- Socket 与ServerSocket区别
- Android平台锁屏设计说明
- cocos2d中CCSprite的使用总结
- boost::lexical_cast 的使用
- Oracle11g快捷复制数据库
- 内外网同时访问,我的拿来主义
- Uva 10784 - Diagonal
- ucos下用串口做调试口时,接收用户指令的方法
- 相似度法
- 转 win7下android开发环境搭建(win7 64位),32位同理
- (个人原创)zabbix近期监控遇到的一些问题
- 通过Servlet 将服务器硬盘图片 展示到浏览器