Convert int to string

Convert int to string without using itoa in C language

Questions by shyamkumar1221

Showing Answers 1 - 6 of 6 Answers

Use sprintf.

ALternately, you could do something like this (probably not the most efficient approach, but fairly straightforward:

Code
  1. #define MAXDIGITS ... // maximum number of digits that an int type can represent.

  2.                       // Will vary by implementation (16-bit vs. 32-bit vs. 64-bit)

  3.  

  4. /**

  5.  * Precondition: target points to a writable buffer large enough to hold the result

  6.  */

  7. void intToStr(int val, char *target)

  8. {

  9.   char digit[10] = {'0', '1', '2', '3', '4',

  10.                     '5', '6', '7', '8', '9'};

  11.   char stack[MAXDIGITS] = {0};  

  12.   size_t sp = MAXDIGITS;

  13.   size_t i = 0;

  14.   int sign = val < 0;

  15.  

  16.   if (sign)

  17.     val = -val;

  18.        

  19.   while (val)

  20.   {

  21.         stack[--sp] = digit[val%10];

  22.         val /= 10;

  23.   }

  24.  

  25.   if (sign)

  26.     target[i++] = '-';

  27.        

  28.   while (sp < MAXDIGITS)

  29.     target[i++] = stack[sp++];

  30.        

  31.   target[i] = 0;

  32. }

  33.  

  Was this answer useful?  Yes

Oh for Pete's sake, what's the point of having an "insert code" option if it munges the code beyond all recognition? Seriously, for a site geared towards programming questions, the support for actually *posting code* is pretty poor.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions