Skip to content

Instantly share code, notes, and snippets.

@shaobin0604
Created October 29, 2009 08:47
Show Gist options
  • Save shaobin0604/221278 to your computer and use it in GitHub Desktop.
Save shaobin0604/221278 to your computer and use it in GitHub Desktop.
tcpl_ex-1-21.c
/*
* Exercise 1-21. 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?
*/
#include <stdio.h>
#define TABINC 8
int main(void) {
int c, i, j;
i = 0; /* position */
j = 0; /* the space count */
while (EOF != (c = getchar())) {
if (' ' == c) {
j++;
if (0 == (i + j) % TABINC) {
putchar('\t');
i = i + j;
j = 0;
}
} else {
while (j > 0) {
putchar(' ');
i++;
j--;
}
putchar(c);
if ('\t' == c)
i += (TABINC - (i % TABINC));
else if ('\n' == c)
i = 0;
else
i++;
}
}
while (j > 0) {
putchar(' ');
i++;
j--;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment