Page 34

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

#include <stdio.h>

#define TAB_STOP 4

int main()
{
	int c;
	int tab_pos = 0;
	int nb = 0;

	while ((c = getchar()) != EOF) {
		++tab_pos;
		tab_pos %= TAB_STOP;

		if (c == ' ') {
			nb++;
			if (tab_pos == 0) {
				if (nb > 1) {
					putchar('\t');
				} else {
					putchar(' ');
				}
				nb = 0;
			}
		} else {
			for (int i = 0; i < nb; i++) {
				putchar(' ');
			}

			nb = 0;
			if (c == '\n') {
				tab_pos = 0;
			}

			putchar(c);
		}
	}
}