Search code examples
c++hexistringstream

c++ std::istringstream weird std::hex behaviour


EDIT:

I managed to get the same problem on a smaller scale:

std::istringstream hex;
std::string str = "0x7ffa428ab946";
std::cout << "str " << str << std::endl;
hex.str(str);
long caller;
hex >> std::hex >> caller;
std::cout << "caller " << caller << std::endl;
str = "0x7ff9ec0010f0";
std::cout << "str " << str << std::endl;
hex.str(str);
long address;
hex >> std::hex >> address;
std::cout << "address " << address << std::endl;

and get this:

str 0x7ffa428ab946
caller 140712834939206
str 0x7ff9ec0010f0
address 0

why is that?


Solution

  • hex >> std::hex >> caller;
    

    will set eofbit on hex, but the subsequent

    hex.str(str);
    

    doesn't clear it. Thus, later attempts to extract from hex will simply fail.

    Call hex.clear() after the hex.str(str); call to clear the flags.