词汇演员部分转换 - 有可能吗?

时间:2013-07-23 01:55:46

标签: c++ boost

lexical_cast在以下情况下抛出异常。有没有办法使用lexical_cast并将字符串转换为整数。

#include <iostream>
#include "boost/lexical_cast.hpp"
#include <string>
int main()
{
        std::string src = "124is";
        int iNumber = boost::lexical_cast<int>(src);
        std::cout << "After conversion " << iNumber << std::endl;
}

我理解,我可以使用atoi代替boost::lexical_cast

2 个答案:

答案 0 :(得分:1)

boost / lexical_cast使用stringstream从字符串转换为其他类型,因此你必须确保字符串可以完全转换!或者,它会抛出bad_lexical_cast异常,这是一个例子:

#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

    { 

        // ----- string --> int 

        a = lexical_cast<int>("123");//good

        b = lexical_cast<double>("123.12");//good


        // -----double to string good

        s = lexical_cast<std::string>("123456.7"); 

        // ----- bad

        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;    // cout:123 

    std::cout << b << std::endl;    //cout:123.12 

    std::cout << s << std::endl;     //cout:123456.7 

    return 0;

}

答案 1 :(得分:1)

如果我正确理解您的要求,似乎在lexical_cast之前首先从字符串中删除非数字元素将解决您的问题。我在这里概述的方法使用了isdigit函数,如果给定的char是从0到9的数字,它将返回true。

#include <iostream>
#include "boost/lexical_cast.hpp"
#include <string>
#include <algorithm>
#include <cctype> //for isdigit

struct is_not_digit{
    bool operator()(char a) { return !isdigit(a); }
};

int main()
{
    std::string src = "124is";
    src.erase(std::remove_if(src.begin(),src.end(),is_not_digit()),src.end());
    int iNumber = boost::lexical_cast<int>(src);
    std::cout << "After conversion " << iNumber << std::endl;
}