summaryrefslogtreecommitdiffstats
path: root/1/19.c
blob: cba39a3aa4df2d6a24e522b4368717b0a3886da6 (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
#include <stdio.h>

#define MAXLEN 5

int cgetline(char s[], int max);
void reverse(char s[], int size);

/* reverses input string */
int main(int argc, char *argv[]) {
  int size;
  char s[MAXLEN];

  while ((size = cgetline(s, MAXLEN)) > 0) {
    reverse(s, size);
    printf("%s\n", s);
  }

  if (size == -1) {
    printf("exceeded max input size: %d\n", MAXLEN);
    return 1;
  }

  return 0;
}

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

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

  return i == max && c != '\n' && c != EOF ? -1 : i;
}

void reverse(char s[], int size) {
  int i, j, lim;

  lim = size / 2;

  for (i = 0, j = size - i - 1; i < lim; i++) {
    s[i] = s[i] ^ s[j];
    s[j] = s[i] ^ s[j];
    s[i] = s[i] ^ s[j];
  }
}