-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathex_1-19.c
117 lines (84 loc) · 1.85 KB
/
ex_1-19.c
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/*
maxline
function: discard newline
for loop through buffer looking for terminator
if current postion is newline, set position to terminator
function: reverse
for find end of buffer as integer
move back one space
for loop reverse through string printing out chars one at a time
function: getline
for get chars until buffer is full
if last char is newline add to end of buffer
terminate buffer with '\0'
function: main
while getline > 0
disgard new line
reverse line
print line
*/
#include <stdio.h>
#define MAXLEN 1024
/*
loop throguh buffer
convert newlines into nulls marking end of array
*/
int discard(char buffer[])
{
int i;
for(i = 0; buffer[i] != '\0'; i++) /* loop until we find NULL */
{
if(buffer[i] == '\n') { buffer[i] = '\0'; } /* convert newlines into NULL */
}
return 0;
}
/*
reverse
loop through buffer reversing chars
*/
int reverse(char buffer[])
{
char ch;
int i,j;
for(j = 0; buffer[j] != '\0'; ++j) { } /* find length of buffer */
--j; /* move back one space */
/* loop though length of array reversing front to back chars */
for(i = 0; i < j; i++)
{
ch = buffer[i];
buffer[i] = buffer[j];
buffer[j] = ch;
--j;
}
return 0;
}
/*
getine
get input passed to program and store in buffer
check along the way that the input has not run out
do this until we reach a newline and then terminate with NULL
*/
int getline2(char buffer[], int limit)
{
int i;
char c;
for(i = 0; i < limit - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
{
buffer[i] = c;
}
if(c == '\n') { buffer[i++] = c; }
buffer[i] = '\0'; /* terminate string at this position */
return i; /* return number of chars found in this line */
}
int main()
{
char buffer[MAXLEN];
while(getline2(buffer, sizeof buffer) > 0)
{
// printf("getline\n");
discard(buffer);
reverse(buffer);
printf("%s\n", buffer);
}
return 0;
}