Search code examples
c++chararraysunsigned-integeritoa

Unsigned int into a char array. Alternative to itoa?


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!


Solution

  • 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);