boost :: lexical_cast <int>(“ - 138.8468953457983248”)抛出异常</int>

时间:2013-10-18 17:34:25

标签: c++ visual-c++ boost casting

我正在尝试将此数字转换为整数。但是我被抛出了一个bad_cast异常。我不确定最新情况。

2 个答案:

答案 0 :(得分:3)

那是因为价值

-138.8468953457983248

不是整数。

您需要将其转换为浮点值。

    int a = static_cast<double>("-138.21341535");
                 //     ^^^^^^   Cast to double
 // ^^^  You can assign double to an int

Lexical cast会尝试使用字符串中的所有字符。如果剩下任何东西,那就是糟糕的演员。当您尝试将上述内容转换为整数时,它会读取“-138”,但会在生成异常的转换缓冲区中留下“.21341535”。

#include <boost/lexical_cast.hpp>

int main()
{
    std::cout << "Try\n";
    try
    {
        std::cout << boost::lexical_cast<int>("-138.8468953457983248") << "\n";
    }
    catch(boost::bad_lexical_cast const& e)
    {
        std::cout << "Error: " << e.what() << "\n";
    }
    std::cout << "Done\n";
    std::cout << "Try\n";
    try
    {
        std::cout << boost::lexical_cast<double>("-138.8468953457983248") << "\n";
    }
    catch(boost::bad_lexical_cast const& e)
    {
        std::cout << "Error: " << e.what() << "\n";
    }
    std::cout << "Done\n";
}

这:

> g++ lc.cpp
> ./a.out 
Try
Error: bad lexical cast: source type value could not be interpreted as target
Done
Try
-138.847
Done

答案 1 :(得分:0)

boost::lexical_cast<int>需要字符串/字符流参数。 根据您的要求,您可以使用静态演员。

int a = static_cast<int>(-138.21341535);