-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkr_ex1-18.c
57 lines (48 loc) · 1.17 KB
/
kr_ex1-18.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
#include <stdio.h>
#define MAXLINE 1000 // max length of text line
int mygetline(char line[], int maxlength);
void removeTrailSpace(char line[]);
/* remove trailing blakks and tabs at end of lines */
int main()
{
int len; // current line length
char line[MAXLINE]; // current line
while ((len = mygetline(line, MAXLINE)) > 0)
if (len > 1) {
removeTrailSpace(line);
printf("%s", line);
}
}
/* getilne: read a line into s, return its length */
int mygetline(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; // since the for loop exit before putting the newline
++i;
}
s[i] = '\0'; // the end of string character
return i;
}
/* removeTrailSpace: delete tabs and spaces from end of line */
void removeTrailSpace(char s[])
{
int i = 0;
int len;
// finding length of line
while (s[i] != '\0')
++i;
len = i--;
while ((i >= 0) && ((s[i] == ' ') || (s[i] == '\t') || (s[i] == '\n')))
--i;
if (i < 0) {
s[0] = '\0'; // delete the empty line
}
else {
if (s[len - 1] == '\n')
s[++i] = '\n';
s[++i] = '\0';
}
}