Slide 7.5: FixedLen.h
Slide 7.7: Record.h
Home

itoa.h


This is the itoa( int n, char* s ) function, which converts an integer value to a null-terminated string. The least significant digit of an integer n is transformed to a character by using the formula:
   n%10 + '0'
The function reverse( char* s ), used by the itoa( ), reverses the string s, for example, abcdef is reversed to fedcba.

 ~wenchen/public_html/cgi-bin/351/week7/itoa.h 
#include  <cstring>
  using namespace  std;

void  reverse( char* s ) {
  int  c, i, j;
  for ( i = 0, j = strlen( s )-1;  i < j;  i++, j-- ) {
    c    = s[i];
    s[i] = s[j];
    s[j] = c;
  }
}
void  itoa( long n, char* s ) {
  int  i, sign;

  if ( ( sign = n ) < 0 )  n = -n;
  i = 0;
  do {
    s[i++] = n%10 + '0';
  } while ( ( n /= 10 ) > 0 );
  if ( sign < 0 )  s[i++] = '-';
  s[i] = '\0';
  reverse( s );
}