Skip to content

Instantly share code, notes, and snippets.

@yugecin
Forked from sqroot3/entab.c
Last active February 16, 2018 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yugecin/7ff479178b8774f07e0ca1e92a70bd9b to your computer and use it in GitHub Desktop.
Save yugecin/7ff479178b8774f07e0ca1e92a70bd9b 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
// http://forum.sa-mp.com/showthread.php?t=649767
#include <stdio.h>
#define TABSIZE 8
int main()
{
int c, cft, nspaces;
//cft = chars from tab, nspaces = number of spaces buffered
cft = nspaces = 0;
while((c = getchar()) != EOF) {
if(c == '\n') {
// reset ALL the things
cft = nspaces = 0;
putchar(c);
continue;
}
if(c == '\t') {
// treat tabs as spaces to easily minify later
// don't add TABSIZE, calculate the amount of chars to the next tab column
nspaces += TABSIZE - (cft + nspaces) % TABSIZE;
continue;
}
if(c == ' ') {
++nspaces;
continue;
}
//decide whether gap in between chars is long enough for a tab
while(nspaces >= TABSIZE - cft) {
putchar('\t');
nspaces -= TABSIZE - cft;
cft = 0;
}
//insert all remaining spaces manually
while(nspaces > 0) {
putchar(' ');
--nspaces;
++cft;
}
cft = (cft + 1) % TABSIZE;
putchar(c);
}
return 0;
}
@sqroot3
Copy link

sqroot3 commented Feb 16, 2018

Hey! Thanks for the help man! After some discussion on CodeReview on StackExchange, I got some feedback with which I've made the 2nd revision.

A couple of comments just to see if we're on the same track:

  • After while(nspaces > 0, since we're decrementing it in steps of one, we're certain that nspaces must be 0.
  • I like how you are using the % operand to calculate tabsizes, but the line nchars = 0; works to fix the logic error where any line with TABSIZE (8) + nonwhitespace characters would be given extra tabs.
  • I am glad you showed me your version using continue, but the approach in the 2nd version makes more sense to me than this one.

Thanks a lot nonetheless, I am very happy you spent time in helping me :)

@yugecin
Copy link
Author

yugecin commented Feb 16, 2018

  • nspaces can be negative because you check for nspaces >= TABSIZE - nchars but subtract the full TABSIZE Oh I guess you're talking about my code? yeah I removed that statement when I saw that later
  • the nchars = 0 doesn't fix everything I think

I discussed it more thoroughly in my reply
http://forum.sa-mp.com/showthread.php?p=3993467#post3993467

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