アプリ版:「スタンプのみでお礼する」機能のリリースについて

boost::lexical_castで16進数文字列を数値に変換する

次のコードで試しましたが実行時例外になります。
16進数文字列をlexical_castで扱う方法を教えてください。
#include <boost/lexical_cast.hpp>
string ss = "0x1234";
int n = boost::lexical_cast<int>(ss);
よろしくお願いします。

A 回答 (2件)

原則として無理なので、strtolを使ってください。



int n;
errno = 0;
char* endptr;
long temp = std::strtol(ss.c_str(), &endptr, 0);
if (errno != 0 || temp < std::numeric_limits<int>::min() || std::numeric_limits<int>::max() < temp || *endptr != '\0')
{
 // エラー処理
}
    • good
    • 0
この回答へのお礼

回答、ありがとうございます。
代替えコードを参考にさせていただきます。

お礼日時:2010/06/29 08:06

こんな感じで無理すれば出来なくは無いです。



#include <sstream>
#include <iomanip>
#include <boost/lexical_cast.hpp>

template<typename DST>
struct hex_to
{
 operator DST(void) const
 {
  return value;
 }

 DST value;
};

template<typename DST>
std::istream& operator>>( std::istream& ist , hex_to<DST>& h )
{
 std::string s;
 ist >> std::hex >> h.value;
 return ist;
}


int main(int argc, char* argv[])
{
 int i = boost::lexical_cast< hex_to<int> >("0xff");
 std::cout << i << std::endl;

 getchar();
 return 0;
}


ただ、ちょっと複雑すぎるので出来れば避けたほうが良いような気はします。
    • good
    • 0
この回答へのお礼

回答、ありがとうございます。
詳しいコードを示していただき恐縮です。参考にさせていただきます。

お礼日時:2010/06/29 08:07

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!