|
From: Luigi S. <gi...@li...> - 2003-04-01 08:23:18
|
On Tue, Apr 01, 2003 at 02:42:48AM +0000, Khalid El-Kary wrote:
> Hi fellows,
>
> I'm wondering if there's a possible way to turn an integer to its string
> representation in C
>
> //I want to get a string "5" out of f
> int f=5;
>
> thanx in advance.
>
> Regards,
> Khalid Al-Kary
>
Hello Khalid,
You have already been supplied with an excellent solution, here is
another approach, both: less efficient and less elegant; but I'm posting
it anyway because I feel it is an example some newbies (like me) can
probably benefit from.
t_itoa.c
--------
#include <stdio.h>
#include <stdlib.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:\nk = %d\n\n", k);
printf("OUTPUT:\ns = %s\n\n", s);
free(s); /* return memory to the system, as soon as you can */
k = -4567; /* a little harder: using a negative number */
s = itoa(k);
printf("INPUT:\nk = %d\n\n", k);
printf("OUTPUT:\ns = %s\n\n", s);
free(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);
/* invert order of elements in an array */
char *
invert(char *s);
/********************************************************************/
#endif /* not itoa_h */
------
itoa.c
------
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "itoa.h"
#define MAXSZ 21 /* assuming integer is made of 19 digits + sign */
/********************************************************************/
char *
itoa(int n)
{
char * buf = (char *)calloc(MAXSZ, sizeof(char)); /* get memory */
char *p = buf; /* pointer used to sweep across buffer */
char neg = 0; /* 1 means that the integer is negative */
assert(buf != 0); /* check if memory was allocated */
if (n < 0) /* negative integer */
{
n = -n; /* work on its absolute value */
neg = 1; /* turn on the flag */
}
while (n) /* main loop */
{
*p++ = '0' + n % 10; /* char for a digit as offset from '0' */
n /= 10; /* drop last character */
}
if (neg) /* append a negative sign */
*p++ = '-';
*p = '\0'; /* terminate string */
return invert(buf);
}
/********************************************************************/
char *
invert(char *s)
{
char *p = s + strlen(s); /* points the terminating '\0' */
char *q = s - 1; /* points one before first char */
while (--p > ++q)
{
char c = *p; /* classic code used to swap characters */
*p = *q;
*q = c;
}
return s;
}
------
Regards
--
>> gisan >>
|