zoukankan      html  css  js  c++  java
  • boost/lexical_cast.hpp的简单使用方法_行动_新浪博客

    boost/lexical_cast.hpp的简单使用方法_行动_新浪博客

        boost/lexical_cast.hpp的简单使用方法
        (2010-03-19 16:31:13)
        转载▼
        标签:
        杂谈
            分类: C
        1、字符串->数值
        C++代码

            #include <boost/lexical_cast.hpp>  
            #include <iostream>  
            int main()  
            {  
                    using boost::lexical_cast;  
                    int a = lexical_cast<int>("123");  
                    double b = lexical_cast<double>("123.12");  
                     std::cout<<a<<std::endl  
                     std::cout<<b<<std::endl;  
                    return 0;  
            } 




        2、数值->字符串
        C++代码

            #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、异常
        C++代码

            #include <boost/lexical_cast.hpp>  
            #include <iostream>  
            int main()  
            {  
                    using std::cout;  
                    using std::endl;  
                    int i;  
                    try 
                     {  
                         i = boost::lexical_cast<int>("xyz");  
                     }  
                    catch(boost::bad_lexical_cast& e)  
                     {  
                         cout<<e.what()<<endl;  
                        return 1;  
                     }  
                     cout<<i<<endl;  
                    return 0;  
            } 



        显然“xyz”并不能转换为一个int类型的数值,于是抛出异常,捕捉后输出“bad lexical cast: source type value could not be interpreted as target”这样的信息。

        4、注意事项

        lexical_cast依赖于字符流std::stringstream,其原理相当简单:把源类型读入到字符流中,再写到目标类型中,就大功告成。
        C++代码

            int d = boost::lexical_cast<int>("123"); 



        相当于
        C++代码

            int d;  
            std::stringstream s;  
            s<<"123";  
            s>>d; 



        5、小结

        我们已经体验了boost::lexcial_cast。当然,lexical_cast不仅仅局限于字符串类型与数值类型之间的转换:可在任意可输出到stringstream的类型和任意可从stringstream输入的类型间转换。

        ;-)
  • 相关阅读:
    Oracle 的merge into 用法
    个人博客作业——结课总结
    个人博客作业week7
    结对项目总结博客
    #个人博客作业week3——微软必应词典的使用
    #个人博客作业week2——结对编程伙伴代码复审
    #个人博客作业week2——关于代码规范的个人观点
    #个人博客作业——目前流行的源程序版本管理软件和项目管理软件优缺点
    个人项目——四则运算题目的随机生成
    #个人博客作业Week1——浏览教材后提出的六个问题及软件与软件工程的提出。
  • 原文地址:https://www.cnblogs.com/lexus/p/3524894.html
Copyright © 2011-2022 走看看