K&R Solutions - 1.19

Q: Write a function 'reverse(s)' that reverses the character string 's'. Use it to write a program that reverses the input one line at a time.

A:

#include <stdio.h>

// Using the same basic format is previous exercises and examples
#define MAXLINE 1000

int get_a_line(char s[], int lim);
void reverse(char s[]);

int main(void)
{
  char line[MAXLINE];

  while ((get_a_line(line, MAXLINE)) > 0) {
    reverse(line);
    printf("%s", line);
  }

  return 0;
}

int get_a_line(char s[], int lim)
{
  int c, i;

  for (i = 0; i < lim-1 && (c=getchar()) != EOF && c != '\n'; ++i) {
    s[i] = c;
  }

  if (c == '\n') {
    s[i] = c;
    ++i;
  }
  s[i] = '\0';

  return i;
}

void reverse(char s[])
{
  char temp[MAXLINE];
  int i, j;

  i = 0;
  while ((temp[i] = s[i]) != '\0')
    ++i;

  /* Reversing the newline looks ugly. In real life, we might strip that 
   * char of whitespace before reversing it, as per the last lesson. */
  j = 0;
  --i;
  s[i--] = '\n';
  while (i >= 0) {
    s[i] = temp[j];
    ++j;
    --i;
  }
}
./reverse 
hi
ih
sananab is a good blog
golb doog a si bananas
tacocat
tacocat