Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/cprogs/Ex_1.22_fold.c
1240 views
1
/* Exercise 1-22: Write a program to "fold" long input lines into two or more
2
shorter lines after the last non-blank character that occurs
3
before the n-th column of input. */
4
5
#include <stdio.h>
6
7
8
#define MAXCOL 35 /* folded line length */
9
#define TABVAL 8 /* standard tab length */
10
#define CURTAB(c) (TABVAL - ((c) % TABVAL)) /* current tab size */
11
#define NO_BLANK -1 /* signifies no blank found */
12
13
int lastblank(const char arr[], int len);
14
15
/* folds long input lines into two or more shorter lines */
16
int main(void)
17
{
18
int c; /* character variable */
19
int i, j; /* indexing variable(s) */
20
int pos; /* current position in array */
21
int col; /* current column of output */
22
int lbc; /* last blank character position */
23
char line[MAXCOL + 1]; /* fold array */
24
25
pos = col = 0;
26
while ((c = getchar()) != EOF) {
27
/* process line array, keep track of line length by columns */
28
line[pos++] = c;
29
col += (c == '\t') ? CURTAB(col) : 1;
30
31
/* create fold */
32
if (col >= MAXCOL || c == '\n') {
33
line[pos] = '\0';
34
35
if ((lbc = lastblank(line, pos)) == NO_BLANK) {
36
/* split word if no blank characters */
37
for (i = 0; i < pos; ++i)
38
putchar(line[i]);
39
/* reset column value and array position */
40
col = pos = 0;
41
}
42
else {
43
/* print array up until last blank character */
44
for (i = 0; i < lbc; ++i)
45
putchar(line[i]);
46
/* feed remaining characters into buffer */
47
for (i = 0, j = lbc + 1, col = 0; j < pos; ++i, ++j) {
48
line[i] = line[j];
49
/* set new column value */
50
col += (c == '\t') ? CURTAB(col) : 1;
51
}
52
/* set array position after remaining characters */
53
pos = i;
54
}
55
/* finish folded line with newline character */
56
putchar('\n');
57
}
58
}
59
60
return 0;
61
}
62
63
/* finds the last whitespace character in an array
64
and returns the position */
65
int lastblank(const char arr[], int len)
66
{
67
int i, lbc;
68
69
lbc = -1;
70
for (i = 0; i < len; ++i)
71
if (arr[i] == ' ' || arr[i] == '\t' || arr[i] == '\n')
72
lbc = i;
73
74
return lbc;
75
}
76
77