|
From: Luigi S. <gi...@li...> - 2003-04-01 21:59:51
|
Hello,
I've revised the previous implementation of "itoa", adding the
enhancements that Per Westmark suggested. The code lacks error
checking, so isn't robust at all.
--
>> gisan >>
t_itoa.c
--------
#include <stdio.h>
#include "itoa.h"
int
main()
{
int k = 123; /* integer value to be converted */
char *s = itoa(k); /* string holding the converted value */
printf("INPUT:\tk = %d\n", k);
printf("OUTPUT:\ts = %s\n\n", s);
k = -4567; /* a little harder: using a negative number */
s = itoa(k);
printf("INPUT:\tk = %d\n", k);
printf("OUTPUT:\ts = %s\n\n", s);
return 0;
}
--------
itoa.h
------
#ifndef itoa_h
#define itoa_h
#pragma defs_in itoa.c /* needed by makefile generator (ignore it) */
/* turn an integer into a string (i.e. an array) */
char *
itoa(int n);
#endif /* not itoa_h */
------
itoa.c
------
#include "itoa.h"
#define MAXSZ 21 /* assuming integer is made of 19 digits + sign */
char *
itoa(int n)
{
static char buf[MAXSZ];
char *p = buf + MAXSZ; /* sweep across buffer */
char neg = 0; /* 1 means that the integer is negative */
if (n < 0) /* negative integer */
{
n = -n; /* work on its absolute value */
neg = 1; /* turn on the flag */
}
*p = '\0'; /* terminate string */
while (n && p > buf) /* main loop */
{
*--p = '0' + n % 10; /* char for a digit as offset from '0' */
n /= 10; /* drop last character */
}
if (neg && p > buf ) /* prepend a negative sign */
*--p = '-';
return p;
}
------
|