Thursday, August 18, 2011

Exercise 1-20

Exercise 1-20  Write a program detab that replaces tabs in the input with the proper number of blanks to space to the next tab stop.  Assume a fixed set of tab stops, say every n columns.  Should n be a variable or a symbolic parameter?

For clarity, I have renamed n to TABSTOP.  If the value is known at compile time then a symbolic parameter seems appropriate.  If it is not, then a variable is best.  Perhaps the value could be given on the command line.

#include <stdio.h>

#define TABSTOP 8

int main(void)
{
  int c;
  int col = 0;

  while (c = getchar(), c!=EOF)
  {
    switch(c)
    {
      /* Should also put \r here and a bunch of other cases. */
    case '\n':
      putchar(c);
      col = 0;
      break;

    case '\t':
      do
      {
        putchar(' ');
        col++;
      }
      while(col%TABSTOP);
      break;

    default:
      putchar(c);
      col++;
      break;
    }
  }

  return 0;
}

No comments:

Post a Comment