Chinaunix首页 | 论坛 | 博客
  • 博客访问: 246932
  • 博文数量: 108
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 314
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-29 10:58
文章分类

全部博文(108)

文章存档

2015年(20)

2014年(88)

我的朋友

分类: C/C++

2014-07-03 17:06:08

1,字符串 到 数值类型的转换

2,数值 到 字符串的转换 
3,异常处理情况 
4,boost::lexical_cast 的原型: 
template 
    Target lexical_cast(Source arg); 
lexical_cast 是依赖于字符串流 std::stringstream 的,其原理也是相当的简单:把源类型 (Source) 读入到字符流中,再写到目标类型 (Target) 中。但这里同时也带来了一些限制: 
  - 输入数据 (arg) 必须能够 “完整” 地转换,否则就会抛出 bad_lexical_cast 异常。例如: 
   int i = boost::lexical_cast("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 
#include 
#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_caststring>("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;
}
阅读(919) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~