Question

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!

Was it helpful?

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

OTHER TIPS

You can simply Make your own function like this one :

Code Link On Ideone using OWN Function

    #include<iostream>
    #include<cstdio>
    #include<cmath>

    using namespace std;

    int main()
    {
        unsigned int num,l,i;

        cin>>num;
        l = log10(num) + 1; // Length of number like if num=123456 then l=6.
        char* ans = new char[l+1];
        i = l-1;

        while(num>0 && i>=0)
        {
            ans[i--]=(char)(num%10+48);
            num/=10;
        }
        ans[l]='\0';
        cout<<ans<<endl;

        delete ans;

        return 0;
    }

You can also use the sprintf function (standard in C)

sprintf(str, "%d", a); //a is your number ,str will contain your number as string

Code Link On Ideone Using Sprintf

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top