Hello there!

How can I convert an INT value into a string?
I used the itoa function successfully in Windows:

itoa(the_int_number, the_string, 10);

It worked fine in Windows (DevC++) but Linux did not recognize this function.

Does anyone know another way of converting INT into char[n] in C that Linux could accept?

Thank you for any hints!

Marcos

Use sprintf function to convert int to string. Thats the more portable way of doing it. Since itoa is not portable!

char *cvtInt( char *str, int num)
{
    sprintf( str, "%d", num );
}

ssharish

The sprintf does not implement itoa functionality (radix in 2..36 range).
Fortunately, it's so simple to get itoa portable solution:

/* The Itoa code is in the puiblic domain */
char* Itoa(int value, char* str, int radix) {
    static char dig[] =
        "0123456789"
        "abcdefghijklmnopqrstuvwxyz";
    int n = 0, neg = 0;
    unsigned int v;
    char* p, *q;
    char c;

    if (radix == 10 && value < 0) {
        value = -value;
        neg = 1;
    }
    v = value;
    do {
        str[n++] = dig[v%radix];
        v /= radix;
    } while (v);
    if (neg)
        str[n++] = '-';
    str[n] = '\0';
    for (p = str, q = p + n/2; p != q; ++p, --q)
        c = *p, *p = *q, *q = c;
    return str;
}

That's handy ArkM, but could you provide some references? How do you know the code is in the public domain and where did you get it from?

Also, is it just me or is that code bugged? When n/2 is odd, the for loop continues infinitely as p and q simply bypass each other, so the condition should actually be p<q, right?

Ohh, that's mea culpa... See right code below...
I know that this code is in the public domain because I have wrote it for 5 (or 10;)) minutes 22 days ago. So I have got it directly from my VC++ 2008 solution...

/* The Itoa code is in the public domain */
char* Itoa(int value, char* str, int radix) {
    static char dig[] =
        "0123456789"
        "abcdefghijklmnopqrstuvwxyz";
    int n = 0, neg = 0;
    unsigned int v;
    char* p, *q;
    char c;

    if (radix == 10 && value < 0) {
        value = -value;
        neg = 1;
    }
    v = value;
    do {
        str[n++] = dig[v%radix];
        v /= radix;
    } while (v);
    if (neg)
        str[n++] = '-';
    str[n] = '\0';

    for (p = str, q = p + (n-1); p < q; ++p, --q)
        c = *p, *p = *q, *q = c;
    return str;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.