summaryrefslogtreecommitdiffstats
path: root/3/6.c
blob: bb3636f1e02e3a1f8b05cd2d9f430ee4310ed0e6 (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
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXLEN 1000

/* converts n to s with width w */
void itoa(int n, char s[], int w);

int main(int argc, char *argv[]) {
  int i, c, n, w;
  char s[MAXLEN];

  printf("Number to convert to string: ");
  for (i = 0; i < MAXLEN - 1 && (c = getchar()) != '\n' && c != EOF; i++)
    s[i] = c;
  s[i] = 0;
  n = atoi(s);

  printf("Width: ");
  for (i = 0; i < MAXLEN - 1 && (c = getchar()) != '\n' && c != EOF; i++)
    s[i] = c;
  s[i] = 0;
  w = atoi(s);

  itoa(n, s, w);
  printf("%d as string of width %d: %s\n", n, w, s);

  return 0;
}

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(int n, char s[], int w) {
  int i;

  i = 0;

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

  if (n < 0)
    s[i++] = '-';

  while (i < MAXLEN - 1 && i < w)
    s[i++] = ' ';

  s[i] = 0;

  reverse(s);
}