Skip to main content

1-21

Quest: page 34


Write a program entab that replaces strings of blanks by the minimum number of tabs and blanks to achieve the same spacing. Use the same tab stops as for detab . When either a tab or a single blank would suffice to reach a tab stop, which should be given preference ?


  • check if there are x blanks in a line then replace it wwith a tab where X is the number of spaces for a tab
  • IF x SPACES THEN print tab ELSE print blanks
  • I didn't use a buffer i just counted each time i see a blank
#include <stdio.h>

#define TABSPACE 8

int main() {
int c;
int i = 0;
while ((c = getchar()) != EOF) {
if (c == ' ') {
// white space detected check if X spaces or not
for (i = 0; i < TABSPACE; i++) {
c = getchar();
if (c != ' ') {
break;
}
}
if (i == (TABSPACE - 1)) {
putchar('\t');
putchar(c);
} else {
// print the spaces == i +1
for (int j = 0; j < i + 1; j++) {
putchar(' ');
}
putchar(c);
}
i = 0;
} else {
putchar(c);
}
}
}