Wednesday, August 17, 2011

Exercise 1-18

Exercise 1-18  Write a program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines.

This is one possible answer.  It can buffer up to 100 blanks.  If there are more than 100 blanks in a row, the buffer is flushed.  This behaviour could be improved upon.

#include <stdio.h>

int bufpos = 0;
char buffer[100];

void clear_buffer(void)
{
  bufpos = 0;
}

void flush(void)
{
  int i;
  for (i = 0; i < bufpos; ++i)
    putchar(buffer[i]);

  clear_buffer();
}

void push(char c)
{
  buffer[bufpos++] = c;
  if (bufpos==100)
    flush();
}

void display(char c)
{
  flush();
  putchar(c);
}

void strip(char c)
{
  switch(c)
  {
  case ' ':
  case '\t':
    push(c);
    break;

  case '\n':
    clear_buffer();
    putchar(c);
    break;

  default:
    display(c);
    break;
  }
}

int main(void)
{
  int c;
  int newline = 1;

  while (c=getchar(), c!=EOF)
  {
    if (!newline || c!='\n')
    {
      newline = 0;
      strip(c);
    }

    if (c=='\n')
      newline = 1;
  }

  return 0;
}

No comments:

Post a Comment