Mega Code Archive
A function to return a string representation of an integer with a given width
/*
Beginning C, Third Edition
By Ivor Horton
ISBN: 1-59059-253-0
Published: Apr 2004
Publisher: apress
*/
#include
/* Convert an integer to a string with a fixed width. */
/* if the widh is too small, the minimum width is assumed. */
char* itoa(int n, char str[], int width)
{
int i = 0; /* Loop counter */
int j = 0; /* Loop counter */
int negative = 0; /* Indicate negative integer */
int length = 0; /* Length of string */
int temp = 0; /* Temporary storage */
if(negative = (n<0)) /* Is it negative? */
n = -n; /* make it positive */
/* Generate digit characters in reverse order */
do
{
str[i++] = '0'+n%10; /* Create a rightmost digit */
n /= 10; /* Remove the digit */
}while(n>0); /* Go again if there's more digits */
if(negative) /* If it was negative */
str[i++] = '-'; /* Append minus */
str[i] = '\0'; /* Append terminator */
length = i; /* Save the length */
/* Now reverse the string in place */
/* by switching first and last, */
/* second and last but one, etc */
for(i = 0 ; ilength)
{
for(i=length, j = width ; i>= 0 ; i--, j--)
str[j] = str[i];
for(i = 0 ; i