首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Lexical_cast抛出异常

Lexical_cast抛出异常
EN

Stack Overflow用户
提问于 2019-07-01 08:41:47
回答 1查看 285关注 0票数 0

boost::lexical_cast在将字符串转换为int8_t时抛出异常,但int32_t - norm。

int8_t有什么问题?

代码语言:javascript
复制
#include <iostream>
#include <cstdlib>
#include <boost/lexical_cast.hpp>

int main()
{
    try
    {
        const auto a = boost::lexical_cast<int8_t>("22");
        std::cout << a << std::endl;
    }
    catch( std::exception &e )
    {
        std::cout << "e=" << e.what() << std::endl;
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-01 09:02:53

对于boost::lexical_cast,假定底层流的字符类型为char,除非源或目标需要宽字符流,在这种情况下,底层流使用wchar_t。

助推词法

因此,在做完下面的代码更改之后:

代码语言:javascript
复制
#include <iostream>
#include <cstdlib>
#include <boost/lexical_cast.hpp>

int main() 
{
   try
   {
       const auto a = boost::lexical_cast<int8_t>("2");
       const auto b = boost::lexical_cast<int16_t>("22");
       std::cout << a << " and "<< b << std::endl;
   }
   catch( std::exception &e )
   {
      std::cout << "e=" << e.what() << std::endl;
   }
 return 0;
}

给出以下输出

2和22

所以,我觉得每个字符都被看作是char

因此,对于const auto a = boost::lexical_cast<int16_t>("2"); 2,将其视为需要int8_t的单个char

对于const auto b = boost::lexical_cast<int16_t>("22"); 22,则将其作为两个需要int16_t的char值。

希望能帮上忙!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56832513

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档