/***************************************** 
** File: reverse-broken.c
** Author: Marie desJardins
** Date: October 18, 2006
** E-Mail: mariedj@cs.umbc.edu 
** 
** Contains a program to reverse the words in a string, that
** doesn't quite work...
**
** The program should read in a string, which is assumed to
** contain only letters (alphabetic characters) and white space.
** The program should reverse each word individually, and print
** out the reversed words.
*****************************************/ 


#include <stdio.h>
#include <string.h>
#include <ctype.h>

void scanline (char *s);

int main () {
  char s[100], temp;
  int i, j, nextSpace;

  /* Read the string to be reversed */
  printf ("Enter string: ");
  scanline (s);

  /* Reverse the string */
  i=0;        /* Assume the string starts with a non-space... */
  while ( s[i] != NULL ) {        /* Keep going to the end of the string */
    for ( j=i ; isalpha((int)s[j]) ; j++ )    /* Find the end of this word */
      ;
    nextSpace = j;
    j--;
    for ( ; i < j ; i++ ) {   /* Go forward from the start of the word */
      temp = s[i];
      s[i] = s[j];            /* Swap the characters */
      s[j] = temp;
      j--;                    /* Go back from the end of the word */
    }
    i = nextSpace;
    /* Skip to the next word */
    while ( s[i] && ( ! isalpha((int)s[i]) ) ) { 
      i++;
    }
  }

  /* Print the answer */
  printf ("Reversed words: \"%s\"\n", s);

  return (0);

}











/***************************************** 
 * Function: scanline
 * Usage: scanline (char *s)
 * 
 * Read a string from the input, up to a newline character
 * 
 * Input: s, a pointer to a character array
 * Output: s will be filled with the input string
*****************************************/

void scanline (char *s) {
  int i=0;

  /* Read characters from the input until end-of-line is reached */
  do {
    scanf ("%c", &s[i]);
    i++;
  } while (s[i-1] != '\n');

  /* Set the end-of-string character */
  s[i-1] = NULL;
}
