2013-10-18 67 views

回答

3

这是因为值

-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 
+0

你是说-138.8468953457983248太长?我只想要结果中的值-138。 – user758114

+3

@ user758114:**否**。我说这不是一个整数。词法转换使用'operator >>'来读取字符串。当它打到不是一个整数的'.'时,它会停止阅读。如果缓冲区中还有任何东西,boost lexical_cast将会抛出。因为上面不是整数,所以有些东西留在缓冲区中。 –

0

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

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

即时通讯使用字符串 – user758114