4

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!

Ganjira
  • 966
  • 5
  • 16
  • 32

2 Answers2

4

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);
suspectus
  • 16,548
  • 8
  • 49
  • 57
2

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

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
S J
  • 3,210
  • 1
  • 22
  • 32
  • Not reinvent the wheel, use well documented standard library solutions instead, like `std::stringstream` or `std::to_string()`. – Manu343726 Jun 16 '13 at 13:59
  • 2
    i am not trying to reinvent the wheel. i just told what i know(what i use in my programming ).. more importantly. this is not wrong. so there is no need of down vote for that .. anyways thanks for that :) ! – S J Jun 16 '13 at 14:11
  • Well, is not wrong, but the key concept (Use libraries vs reimplement everithing) is wrong. But, well you are right and that not implies a votedown. Sorry. The 8-min period passed and I can't undo the downvote :( – Manu343726 Jun 16 '13 at 14:15
  • No. there is no need for upvoting now!. i don't know C++ 11. i only know c++ 4.3.2 so you are right ! – S J Jun 16 '13 at 14:19
  • @Shashank_Jain - +1 i agree with you for not using GMP library they don't allow that in programming contests ! –  Jun 18 '13 at 13:24