aboutsummaryrefslogtreecommitdiff
path: root/ch1/1-19_reverse-lines.c
blob: d87b625a71753f124579af9a9c49b8d09f2bb0bb (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
#include <stdio.h>

#define MAXLINELENGTH 9001

int get_line(char s[], int limit) {
	int c, i;

	for (i = 0; i < limit && (c = getchar()) != EOF && c != '\n'; ++i) {
		s[i] = c;
	}

	s[i] = '\0';

	/* If I don't include this check, I can't handle blank lines */
	if (c == EOF && i == 0) {
		return -1;
	} else {
		return i;
	}

}

/* Directly reverse a line's contents. */
void reverse(char input[], int size) {
	int tmp;
	int i = 0;
	size--;

	/* If len and i are the same, then there's no reason to proceed */
	while (size > i) {
		// Store the first character in a temporary spot...
		tmp = input[i];

		// ... and swap!
		input[i] = input[size];
		input[size] = tmp;

		// Bring our numbers closer together
		++i;
		--size;
	}
}

int main(void) {
	// An int and a string to store each line's data in
	int line_len;
	char buffer[MAXLINELENGTH];

	while ((line_len = get_line(buffer, MAXLINELENGTH)) != -1) {
		reverse(buffer, line_len);
		printf("%s\n", buffer);
	}
	return 0;
}