Skip to content

Instantly share code, notes, and snippets.

@sqroot3
Last active February 16, 2018 13:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sqroot3/08aec67a18382416731c5ff41b3997e8 to your computer and use it in GitHub Desktop.
Save sqroot3/08aec67a18382416731c5ff41b3997e8 to your computer and use it in GitHub Desktop.
entab.c - Program that replaces a string of blanks by the min # of spaces & tabs required to generate identical output
#include <stdio.h>
#define TABSIZE 8
int main()
{
int c, nchars, nspaces;
//nchars = number of chars, nspaces = number of spaces
nchars = nspaces = 0;
while((c = getchar()) != EOF) {
if(c == ' ') {
++nspaces;
} else {
//decide whether gap in between chars is long enough for a space
while(nspaces >= TABSIZE - nchars) {
putchar('\t');
nspaces -= TABSIZE;
}
//insert all remaining spaces manually
while(nspaces > 0) {
putchar(' ');
--nspaces;
}
//at this point nspaces has to be 0, update nchars = 0 as well for correct "endpoint" evaluation
nchars = 0;
if(c != '\t') {
++nchars;
}
putchar(c);
}
}
return 0;
}
@sqroot3
Copy link
Author

sqroot3 commented Feb 16, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment