Thursday, August 18, 2011

Exercise 1-19

Exercise 1-19  Write a function reverse(s) that reverses the character string s.  Use it to write a program that reverses its input a line at a time.

I note that there may be better ways of writing a program that reverses its input (such as a recursive function), but this program satisfies the specification exactly.

#include <stdio.h>

#define LINELENGTH 100

int reverse(char *s)
{
  char *end = s;

  while (*end)
    end++;    /* end points to the null. */

  end--;

  while (end>s)
  {
    char temp;
    temp = *end;
    *end = *s;
    *s = temp;

    end--;
    s++;
  }
}

int main(void)
{
  int c;
  int bufpos = 0;
  char buffer[LINELENGTH];

  do
  {
    c = getchar();

    switch(c)
    {
    case '\n':
      buffer[bufpos] = 0;
      reverse(buffer);
      puts(buffer);
      bufpos = 0;
      break;

    case EOF:
      buffer[bufpos] = 0;
      reverse(buffer);
      printf("%s", buffer);
      break;

    default:
      buffer[bufpos++] = c;
      if (bufpos == LINELENGTH)
      {
        printf("Buffer overflow.\n");
        return 1;
      }
      break;
    }
  }
  while(c!=EOF);

  return 0;
}



No comments:

Post a Comment