【问题标题】:boost::lexical_cast<int> ("-138.8468953457983248") Throws exceptionboost::lexical_cast<int> ("-138.8468953457983248") 抛出异常
【发布时间】:2013-10-18 17:34:25
【问题描述】:

我正在尝试将此数字转换为整数。但是我抛出了一个 bad_cast 异常。我不确定发生了什么。

【问题讨论】:

  • 为什么需要投射它?它已经是int
  • 错了,它是一个字符串。
  • @user758114:请只将代码复制并粘贴到 Stack Overflow 中。永远不要重新输入任何内容。
  • 请出示您的代码

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


【解决方案1】:

那是因为价值

-138.8468953457983248

不是整数。

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

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

词法转换将尝试使用字符串中的所有字符。如果有任何剩余,那就是糟糕的演员阵容。当您尝试将上述内容转换为整数时,它会读取“-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

【讨论】:

  • 你是说 -138.8468953457983248 太长了吗?我只想要结果中的值 -138。
  • @user758114:。我说它不是整数。词法转换使用operator&gt;&gt; 来读取字符串。当它到达不是整数的. 时,它会停止读取。 boost lexical_cast 如果缓冲区中还有任何内容将抛出。因为上面不是整数,所以缓冲区中还剩下一些东西。
【解决方案2】:

boost::lexical_cast&lt;int&gt; 需要一个字符串/字符流参数。 根据您的要求,您可以使用静态转换。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多