Blob


1 /*
2 * 1-19. Write a function reverse(s) that reverses the character string s.
3 * Use it to write a program that reverses its input a line at a time.
4 */
6 /* MAXLINE has been reduced for easier testing */
7 #include <stdio.h>
8 #define MAXLINE 1000
10 int getlin(char line[], int maxline);
11 void copy(char to[], char from[]);
12 int strln(char s[]);
13 void rverse(char s[]);
15 main()
16 {
17 int len; /* current line length */
18 char line[MAXLINE]; /* current input line */
20 while ((len = getlin(line, MAXLINE)) > 0) {
21 rverse(line);
22 printf("%s\n", line);
23 }
24 return 0;
25 }
27 int strln(char s[])
28 {
29 int i;
30 for (i=0; s[i] != '\0'; ++i)
31 ;
32 return i;
33 }
35 void rverse(char s[])
36 {
37 int i, len;
38 char c;
39 len = strln(s);
41 for (i = 0; i < len/2; ++i) {
42 c = s[i];
43 s[i] = s[len-1-i];
44 s[len-1-i] = c;
45 }
46 }
48 int getlin(char s[], int lim)
49 {
50 int c, i;
52 for (i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
53 s[i] = c;
54 if (c == '\n') {
55 ++i;
56 }
57 s[i] = '\0';
58 return i;
59 }
61 void copy(char to[], char from[])
62 {
63 int i;
64 i = 0;
65 while ((to[i] = from[i]) != '\0')
66 ++i;
67 }