-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1-21-entab.c
62 lines (51 loc) · 1.58 KB
/
1-21-entab.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
#include <stdio.h>
#define TABWIDTH 8
int main()
{
int charInLine, charsToTab, consecutiveSpaces, c;
charInLine = 0;
consecutiveSpaces = 0;
while ((c = getchar()) != EOF) {
if (c == ' ') {
consecutiveSpaces++;
} else {
if (consecutiveSpaces > 0) {
int tabs, spaces, i, spacesUntilTabstop;
// is the number of tabs to get to the current char less than the number of
// tabs to get to the char + spaces?
if (((charInLine + consecutiveSpaces) / TABWIDTH) > (charInLine / TABWIDTH)) {
spacesUntilTabstop = TABWIDTH - (charInLine % TABWIDTH);
// put a single tab
putchar('\t');
// and update charInLine and consecutiveSpaces
charInLine += spacesUntilTabstop;
consecutiveSpaces -= spacesUntilTabstop;
// now figure out how many tabs we need for the remaining spaces
tabs = consecutiveSpaces / TABWIDTH;
for (i = 0; i < tabs; i++) {
putchar('\t');
charInLine += TABWIDTH; // don't really need to do this as we're always modding
}
// and how many spaces
spaces = consecutiveSpaces % TABWIDTH;
for (i = 0; i < spaces; i++) {
putchar(' ');
charInLine++;
}
} else {
spaces = consecutiveSpaces % TABWIDTH;
for (i = 0; i < spaces; i++) {
putchar(' ');
charInLine++;
}
}
}
consecutiveSpaces = 0;
putchar(c);
charInLine++;
}
if (c == '\n') {
charInLine = 0;
}
}
}