summaryrefslogtreecommitdiff
path: root/ch01/ex19-reverse.c
blob: 71792903b1fe7c75eac3e6b9b14d5a70a27a37f1 (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
#include <stdio.h>
#define MAXLINE 1000	/* maximum input line size */

int getln(char line[], int maxline);
void reverse(char to[], char from[], int len);

/* reverse the input line */
int main()
{
	int len;	/* current line length */
	char line[MAXLINE];	/* current input line */
	char rline[MAXLINE];	/* reversed line */

	while ((len = getln(line, MAXLINE)) > 0) {
		reverse(rline, line, len);
		printf("%s", rline);
	}

	return 0;
}

/* getln:  read a line into s, return length */
int getln(char s[], int lim)
{
	int c, i;

	for (i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
		s[i] = c;
	if (c == '\n') {
		s[i] = c;
		++i;
	}
	s[i] = '\0';
	return i;
}

/* reverse:  reverse the string */
void reverse(char to[], char from[], int len)
{
	int i, nl = 0;

	if (from[len-1] == '\n') {
		nl = 1;
		--len;
	}

	for (i=0; i < len; ++i)
		to[i] = from[len-i-1];

	if (nl == 1) {
		to[i] = '\n';
		++i;
	}

	to[i] = '\0';
}