/*
 * Illustrate the uses of getchar and putchar.
 * Program prompts the user to type two lines of text
 *         the first line is read character-by-character
 *             and immediately echoed to the terminal
 *         the second line is read character-by-character into an array
 *             a null character is added at the end of input
 *             after all reading is done, the array is printed as a string
 */

#include <stdio.h>

#define LINE_SIZE 80

int
main (void)
{
  int a;

  printf ("Enter a line of text: ");

  /* read character by character until new line (\n) is read */  
  a = getchar();                                     /* get first character */
  
  if (a == EOF) {                         /* check for error or end-of-file */
    printf("error or no input");
    return 0;
  }

  printf ("line read:  ");
  while (a != '\n')
  {
    putchar (a);                                   /* echo previous character */
    a = getchar();                                     /* get first character */

    if (a == EOF) {                         /* check for error or end-of-file */
      printf("error or no input");
      return 0;
    }
  }
  putchar ('\n');               /* reading of line done, so move to next line */
  

  char line[LINE_SIZE+1];         /* buffer of LINE_SIZE  plus null character */
  int index = 0;

  printf ("Enter a second line of text (no more than %d characters): ",
          LINE_SIZE);
  
  /* loop combines reading, placing in array and newline check */
  do {
    a = getchar();                                      /* get next character */

    if (a == EOF) {                         /* check for error or end-of-file */
      printf("error or no input");
      return 0;
    }
    
    line[index++] = a;        /* assign character into array, advancing index */
  } while (a != '\n');

  line[index-1] = 0;/* newline char at end--replace by null for end of string */

  printf ("second line read:  %s\n", line);         /* print line as a string */

  return 0;
} // main
