Convert Number

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
Fresh
New poster
Posts: 46
Joined: Mon Apr 15, 2002 10:42 am
Contact:

Convert Number

Post by Fresh »

Hi,

I'm looking for the fastest algorithm to convert an unsigned int to string in format x,x,x,x,x. Thanks...

Code: Select all


void convert(unsigned int, char *buf)
{
    // need help
    ....
    ....
    ....
}

void main()
{
    char buf[1024];
    unsigned int x = 2123456;

    convert(x, buf);
    printf("%s\n", buf);    // buf = 2,123,456
}
- novice :-?

Adil
Learning poster
Posts: 57
Joined: Sun Sep 29, 2002 12:00 pm
Location: in front of the monitor :-)
Contact:

Post by Adil »

hi. i would try with the following.

Code: Select all

void convert(unsigned int  val, char *out)
{
    char str[15], *s = str;
    int len=0;

    if(!val)
    {
        *out++ = '0';
        *out = 0;
        return;
    }

    while(val)
    {
        if(len%3 == 0 && len)
        {
            *s++ = ',';
        }
        *s++ = val%10 + '0';
        val /= 10;
        len++;
    }

    while(--s >= str)
    {
        *out++ = *s;
    }
    *out = 0;
}
i would like to know of a faster procedure.

Fresh
New poster
Posts: 46
Joined: Mon Apr 15, 2002 10:42 am
Contact:

...

Post by Fresh »

Thanks....

- novice :wink:

Post Reply

Return to “C++”