Unsigned int into a char array. Alternative to itoa?
Asked Answered
A

2

5

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!

Allsun answered 16/6, 2013 at 10:40 Comment(2)
There is std::to_string in <string> in C++11.Bliss
@Bliss Worth noting: GCC as of current (4.9.2) and a couple of versions before lacks std::to_string (known library defect).Exoenzyme
H
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);
Homestead answered 16/6, 2013 at 10:49 Comment(0)
L
3

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

Leahleahey answered 16/6, 2013 at 10:57 Comment(6)
Not reinvent the wheel, use well documented standard library solutions instead, like std::stringstream or std::to_string().Kunkel
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 :) !Leahleahey
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 :(Kunkel
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 !Leahleahey
@Shashank_Jain - +1 i agree with you for not using GMP library they don't allow that in programming contests !Goraud
worked for unsigned int range, is there a way to improve it and convert bigger values for unsigned long ?Scrotum

© 2022 - 2024 — McMap. All rights reserved.