Thursday, August 18, 2011

Exercise 1-21

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?

I guess the answer to the latter part of the question is that I would work out what my priority is: compatibility of file format, need for WYSIWYG printing, performance in printing, performance in displaying on screen, etc.  I would then make the decision accordingly.

#include <stdio.h>

#define TABSTOP 8

int column = 0;
static unsigned int blanks = 0;

void pushblank(void)
{
  blanks++;
}

void popblanks(void)
{
  unsigned int desired_column = column+blanks;
  unsigned int desired_tabspace = desired_column / TABSTOP;
  unsigned int present_tabspace = column / TABSTOP;

  while (desired_tabspace > present_tabspace)
  {
    unsigned int blanks_consumed = ((present_tabspace+1) * TABSTOP) - column;

    putchar('\t');
    column+= blanks_consumed;
    blanks-= blanks_consumed;
    present_tabspace++;
  }

  while (blanks)
  {
    putchar(' ');
    column++;
    blanks--;
  }
}

int main(void)
{
  int c;

  while (c=getchar(), c!=EOF)
    switch(c)
    {
    case ' ':
      pushblank();
      break;

    /* Should have cases for \r, \b and a few other things here too. */

    case '\n':
      column = 0;
      putchar(c);
      break;

    default:
      popblanks();
      putchar(c);
      column++;
      break;
    }

  popblanks();

  return 0;
}

No comments:

Post a Comment