boost实战问题分享:bad lexical cast: source type value could not be interpreted as target

一、问题的背景

通过CGI获取某条流的FPS,如: http://172.16.7.76/Image.I0.Stream.FrameRate

 该CGI在IE上返回值如下:

Image.I0.Stream.FPS=0


利用curl获取该返回值,并把返回值按“=”划分,把等号右边的值存入我们的value变量中。

std::string CurlResponse;

....

 boost::algorithm::split( NameValuePair, CurlResponse, boost::algorithm::is_any_of("=") );

std::string value = NameValuePair[1];

 int FPS=( boost::lexical_cast< int > )(value); 


调试程序发现:  

bad lexical cast: source type value could not be interpreted as target。

也就是说: int FPS=( boost::lexical_cast< int > )(value) 在进行boost::lexical_cast时抛出了异常。

二、问题分析

百思不得其解,打印出value的字符值发现也是一个整数的样子,如5 ;

为什么将其转换为整数就有问题呢?仔细观察发现,5后面有几个空格。

经过分析,CGI的返回值每一行之后是带有回车和换行操作符的。也就是说,curlResponse后带有“\r\n”.

通过打印是看不出来的。这样就导致了异常的发生。

三、问题的解决:

将”\r\n"从被转换的字符中剔除即可。

  std::vector< std::string> NameValuePair;
  std::vector< std::string> NameValueEntity;
  boost::algorithm::split( NameValueEntity, CurlResponse, boost::algorithm::is_any_of(“\r\n") );
  boost::algorithm::split( NameValuePair, NameValueEntity[0], boost::algorithm::is_any_of("=") );


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值