tags:

views:

343

answers:

2

I have an existing std::string and an int. I'd like to append the int to the string, but in human readable form (hex notation), rather than in binary gibberish.

Normally, I'd just use printf, but I can't do this with a std:: string (can I?)

Any suggestions as to how to do this?

Example: 
Given:   
   std::string - "Your
   Id Number is: "   int - 0xdeadc0de
Output:   
   std::string - "Your Id Number is: 0xdeadc0de"
+12  A: 

Use a stringstream. You can use it as any other output stream, so you can equally insert std::hex into it. Then extract it's stringstream::str() function.

std::stringstream ss;
ss << "your id is " << std::hex << 0x0daffa0;
const std::string s = ss.str();
xtofl
std::showbase should be used in addition to std::hex to exactly match the OP's requirement of prefixing the int's representation with "0x"
Éric Malenfant
+2  A: 

Building on xtofl's answer, the header you're looking for is <iomanip>. This is where std::hex, std::dec, and std::oct live, all of which can be directed into streams such that whatever gets sent into the stream after them is converted to that base.

Meredith L. Patterson