簡體   English   中英

提高:: lexical_cast的 <signed char> 不能處理負數?

[英]boost::lexical_cast<signed char> cannot handle negative numbers?

這個簡短的C ++程序表現得讓我感到困惑:

#include <cassert>
#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>

int main(void) {
    signed char c = -2;
    assert(c == -2);
    c = boost::lexical_cast<signed char>(std::string("-2"));
    std::cout << c << "\n";
}

使用g++ 5.2.1boost-1.58.0 ,我得到:

在拋出'boost :: exception_detail :: clone_impl>'的實例后調用終止what():錯誤的詞法強制轉換:源類型值無法解釋為目標

為什么不能將字符串“-2”中的Boost強制轉換為帶signed char ,因為值-2可由此類型表示?

解決方案是使用Boost:

#include <boost/lexical_cast.hpp>
#include <boost/numeric/conversion/cast.hpp>
int tmp = boost::lexical_cast<int>(std::string("-2"));
char c = boost::numeric_cast<signed char>(tmp);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM