Unsigned int into a char array. Alternative to itoa?

Ganjira picture Ganjira · Jun 16, 2013 · Viewed 11.7k times · Source

I have a question about unsigned ints. I would like to convert my unsigned int into a char array. For that I use itoa. The problem is that itoa works properly with ints, but not with unsigned int (the unsigned int is treaded as a normal int). How should I convert unsigned int into a char array?

Thanks in advance for help!

Answer

suspectus picture suspectus · Jun 16, 2013

using stringstream is a common approach:

#include<sstream>
...

std::ostringstream oss;
unsigned int u = 598106;

oss << u;
printf("char array=%s\n", oss.str().c_str());

Update since C++11 there is std::to_string() method -:

 #include<string>
 ...
 unsigned int u = 0xffffffff;
 std::string s = std::to_string(u);