Unsigned int into a char array. Alternative to itoa?

12,066

Solution 1

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

Solution 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

Share:
12,066
Ganjira
Author by

Ganjira

Updated on August 21, 2022

Comments

  • Ganjira
    Ganjira over 1 year

    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!

  • Manu343726
    Manu343726 almost 11 years
    Not reinvent the wheel, use well documented standard library solutions instead, like std::stringstream or std::to_string().
  • S J
    S J almost 11 years
    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 :) !
  • Manu343726
    Manu343726 almost 11 years
    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 :(
  • S J
    S J almost 11 years
    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 !
  • Admin
    Admin almost 11 years
    @Shashank_Jain - +1 i agree with you for not using GMP library they don't allow that in programming contests !