Hatena::Groupcprogramming

てーげーC言語

2009-02-18

3-6

| 03:00

#include <stdio.h>
#include <string.h>

void reverse(char s[])
{
  int i, j;
  char temp, *p; 

  i = j = 0;
  p = s;
  

  while(*p++) {
    i++;
  }   
  --i;
  while(i > j) {
    temp = *(s+i);
    *(s+i) = *(s+j);
    *(s+j) = temp;
    i--;
    j++;
  }
}

void itoa(int n, char s[], int field_size)
{
  int i, sign, len;

  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';
  
  len = strlen(s);
  while (len < field_size) {
    s[i++] = ' ';
    s[i] = '\0';
    len++;
  }

  reverse(s);
}

int main()
{
  char s[128];

  itoa(100, s, 5);
  printf("%s\n", s);
  itoa(100, s, 3);
  printf("%s\n", s);

  return 0;
}
# ./a.out                 
  100
100