0

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.

4

2 回答 2

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;

}
于 2013-07-23T03:41:00.457 回答
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;
}
于 2013-07-23T07:34:24.517 回答