summaryrefslogtreecommitdiffstats
path: root/4/12.c
blob: 9d5a0e22959ac15381653c0b47b7d6964e7a3cd9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXLEN 100

void mitoa(int, char[]);
int mgetline(char[], int);

int main() {
  int n;
  char s1[MAXLEN], s2[MAXLEN];

  while (mgetline(s1, MAXLEN)) {
    n = atoi(s1);
    memset(s2, 0, sizeof(s2));
    mitoa(n, s2);
    printf("\t%s\n", s2);
  }

  return 0;
}

int step = 0;

void mitoa(int n, char s[]) {
  if (step >= MAXLEN - 1) {
    s[MAXLEN - 1] = 0;
    printf("error: number too large.\n");
    return;
  }

  if (n < 0) {
    s[step++] = '-';
    n = -n;
  }

  if (n / 10)
    mitoa(n / 10, s);
  s[step++] = n % 10 + '0';
}

int mgetline(char s[], int max) {
  int c, i;

  step = 0;
  
  for (i = 0; i < max - 1 && (c = getchar()) != '\n' && c != EOF; i++)
    s[i] = c;
  s[i] = 0;
  
  return c != '\n' && c != EOF ? -1 : i - 1;
}