1

I am trying to transform a string to a boost::uint64_t the contents of pvalue are 12345678901234567890. the code I'm using right now is:

void setAttribute(EnumAttrTyoe pname, const void *pvalue) {
    if (pname == SESS_ID) {
        const char *raw_sess_id = reinterpret_cast<const char*>(pvalue);
        std::string str_sess_id(raw_sess_id);
        std::cout << "Trying to open session id: '" << str_sess_id << "'\n";
        m_session_id = boost::lexical_cast<unsigned long long>(str_sess_id);
    }
}

This one throws an exception with message "bad lexical cast: source type value could not be interpreted as target." If instead I use this code:

void setAttribute(EnumAttrTyoe pname, const void *pvalue) {
    if (pname == SESS_ID) {
        const char *raw_sess_id = reinterpret_cast<const char*>(pvalue);
        std::string str_sess_id(raw_sess_id);
        std::stringstream ss;
        ss << raw_sess_id;
        ss >> m_session_id;
    }
}

it goes through but the value of m_session_id is 0. I have not yet check the flags of ss but I don't need to be a genious to know it fails. Any ideas what to do now?

UPDATE No C++11, since I cannot use it, and my compiler is VC++ 2008, boost version 1.43.0.

4

2 回答 2

0

这段代码对我有用:

#include <sstream>
#include <cstdint>
#include <iostream>

int main()
{
   std::stringstream ss;
   ss << "12345678901234567890";

   std::uint64_t n = 0;
   ss >> n;

   std::cout << n << "\n";
}

http://liveworkspace.org输出:

标准输出:12345678901234567890

于 2013-03-18T14:17:11.297 回答
0

我认为您输入的 C 样式字符串不是您认为的那样。boost::lexical_cast在 boost 1.42 上,这种用法对我有用:

#include <iostream>
#include <boost/lexical_cast.hpp>
#include <boost/cstdint.hpp>

int main() {
   std::string s = "12345678901234567890";
   boost::uint64_t i = boost::lexical_cast<boost::uint64_t>(s);
   std::cout << i << '\n';
   return 0;
}

我的猜测是您的输入不是以零结尾的,具有您不期望的后缀,或者具有像 UTF16 这样的替代编码。或者它甚至不是一个字符串。

于 2013-03-18T15:39:48.667 回答