Boost::Lexical_cast 的使用

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值