Tuesday, 15 March 2011

c - understanding detab in K&R -



c - understanding detab in K&R -

i'm teaching myself c , working through k&r. i'm doing exercise 1-20:

write programme entab replaces strings of blanks minimum number of tabs , blanks acheive same spacing. utilize same tab stops detab.

i worked through programme myself, reviewing other solutions:

#include<stdio.h> #define tabinc 8 int main(void) { int nb,pos,c; nb = 0; pos = 1; while((c=getchar())!=eof) { if( c == '\t') { nb = tabinc - (( pos - 1) % tabinc); // <---- how work while( nb > 0) { putchar('#'); ++pos; --nb; } } else if( c == '\n') { putchar(c); pos = 1; } else { putchar(c); ++pos; } } homecoming 0; }

i have difficulty understanding how part works nb = tabinc - (( pos - 1) % tabinc);. can please explain doing step step? perhaps walk me through example?

thank you.

consider next input text:

\tone\ntwo\tthree\nsixteen\tseventeen\teighteen\n

this want produce (tabs replaced ···):

column: | | | | 123456789012345678901234567890123 line: 1 ········one 2 two·····three 3 sixteen·seventeen·······eighteen

the number of spaces required each tab character going number 1 tabinc (i.e., 8) inclusive. tabs in above illustration expanded follows:

class="lang-none prettyprint-override">current next tab no. spaces column# position required 1 9 8 4 9 5 8 9 1 18 25 7

you should able see pattern here. if @ tab position (1, 9, 17, etc.), need add together 8 spaces. , in general, if n characters past tab position (where 0 <= n <= 7), need add together 8-n spaces.

we can calculate n easily:

n = (pos - 1) % 8

so nb (the number of spaces need add) can calculated follows:

nb = 8 - n

hence

nb = 8 - ((pos - 1) % 8)

or, more generally,

nb = tabinc - ((pos - 1) % tabinc)

c tabs modulo kernighan-and-ritchie entab-detab

No comments:

Post a Comment