#1
  1. No Profile Picture
    Senior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2001
    Posts
    42
    Rep Power
    0

    casting ints to string


    Is there a way to cast an int to a string? thanks
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2002
    Location
    new york
    Posts
    84
    Rep Power
    13

    C-Style


    Prototype:
    char * itoa ( int value, char * buffer, int radix );

    Parameters:
    value
    Value to be represented as a string. buffer
    Buffer where to store the resulting string. radix
    Numeral radix in which value has to be represented, between 2 and 36.


    /* itoa example */
    #include <stdio.h>
    #include <stdlib.h>

    int main ()
    {
    int i;
    char buffer [33];
    printf ("Enter a number: ");
    scanf ("%d",&i);
    itoa (i,buffer,10);
    printf ("decimal: %s\n",buffer);
    itoa (i,buffer,16);
    printf ("hexadecimal: %s\n",buffer);
    itoa (i,buffer,2);
    printf ("binary: %s\n",buffer);
    return 0;
    }

    /*
    Output:
    Enter a number: 1750
    decimal: 1750
    hexadecimal: 6d6
    binary: 11011010110
    */
  4. #3
  5. No Profile Picture
    Senior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2001
    Posts
    42
    Rep Power
    0
    thanks but i'm not sure how exactly i'm supposed to use this

    in my class i included #include <stdlib.h>

    and I have this method

    Code:
    string TreeNode::getElemString()
    {
    	int i = this->elem;
    	char buffer [33];
    	itoa (i,buffer,10);
    	return buffer;
    }
    but when I try to compile I get this error:


    TreeNode.cc: In method `class string TreeNode::getElemString()':
    TreeNode.cc:41: implicit declaration of function `int itoa(...)'

    line 41 being itoa (i,buffer,10);

    thanks!
  6. #4
  7. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,638
    Rep Power
    4247
    Why not use the sprintf() function

    Code:
    #include <stdio.h>
    
    int main() {
       int foo = 10;
       char buf[33];
       sprintf(buf, "%d", foo);
    }

IMN logo majestic logo threadwatch logo seochat tools logo