home *** CD-ROM | disk | FTP | other *** search
/ C by Discovery (4th Edition) / C_By_Discovery_4th_Edition.tar / C_By_Discovery_4th_Edition / _DISK_ / ch5 / strngio1.c < prev    next >
C/C++ Source or Header  |  2005-06-16  |  2KB  |  63 lines

  1. /*                         strngio1.c
  2.  *
  3.  *   Synopsis  - Accepts a line of text as input from the keyboard 
  4.  *               and echoes it to the terminal screen.
  5.  *
  6.  *   Objective - To illustrate the use of an array to create a 
  7.  *               string and point out the connection among 
  8.  *               pointers, arrays, and strings.
  9.  */
  10. /* Include Files */
  11. #include <stdio.h>
  12.  
  13. /* Constant Definitions */
  14. #define BUF_SIZE 512
  15.  
  16. /* Function Prototypes*/
  17. int inputstring( char * inputptr, int n);            
  18. /* Accepts input of a line of text from the keyboard and stores it
  19.  * in the array pointed to by inputptr as a string.
  20.  * PRECONDITION:  inputptr contains the address of an array of
  21.  *                characters. n is the number of cells in the array.
  22.  * POSTCONDITION: Returns 0 is the input was successful and -1 if 
  23.  *                the input may have been truncated.
  24.  */
  25.  
  26. int main( void )
  27. {
  28.      char inputarray[BUF_SIZE];                        /* Note 1 */
  29.      int retval;
  30.  
  31.      printf( "Enter a line of text.\n> " );
  32.      retval = inputstring( inputarray, BUF_SIZE );     /* Note 2 */
  33.  
  34.      if ( retval == 0 )
  35.           printf( "Input completed: %s\n", inputarray );
  36.      else
  37.           printf( "Input truncated: %s\n", inputarray );
  38.      return 0;
  39. }
  40.  
  41. /********************************* inputstring() *****************/
  42.  
  43. /* Accepts input of a line of text from the keyboard and stores
  44.  * it in the array pointed to by its argument.
  45.  */
  46. int inputstring( char *buffer, int n )
  47. {
  48.      int i = 0;
  49.                                                        /* Note 3 */
  50.      while ( i <= n-1 && ( buffer[i] = getchar() ) != '\n' ) {
  51.         i++;
  52.      }
  53.  
  54.      if ( i == n ) {                                   /* Note 4 */
  55.           buffer[i-1] = '\0';
  56.           return -1;
  57.      }
  58.      else {                                            /* Note 5 */
  59.           buffer[i] = '\0';
  60.           return 0;
  61.      }
  62. }
  63.