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 >
Wrap
C/C++ Source or Header
|
2005-06-16
|
2KB
|
63 lines
/* strngio1.c
*
* Synopsis - Accepts a line of text as input from the keyboard
* and echoes it to the terminal screen.
*
* Objective - To illustrate the use of an array to create a
* string and point out the connection among
* pointers, arrays, and strings.
*/
/* Include Files */
#include <stdio.h>
/* Constant Definitions */
#define BUF_SIZE 512
/* Function Prototypes*/
int inputstring( char * inputptr, int n);
/* Accepts input of a line of text from the keyboard and stores it
* in the array pointed to by inputptr as a string.
* PRECONDITION: inputptr contains the address of an array of
* characters. n is the number of cells in the array.
* POSTCONDITION: Returns 0 is the input was successful and -1 if
* the input may have been truncated.
*/
int main( void )
{
char inputarray[BUF_SIZE]; /* Note 1 */
int retval;
printf( "Enter a line of text.\n> " );
retval = inputstring( inputarray, BUF_SIZE ); /* Note 2 */
if ( retval == 0 )
printf( "Input completed: %s\n", inputarray );
else
printf( "Input truncated: %s\n", inputarray );
return 0;
}
/********************************* inputstring() *****************/
/* Accepts input of a line of text from the keyboard and stores
* it in the array pointed to by its argument.
*/
int inputstring( char *buffer, int n )
{
int i = 0;
/* Note 3 */
while ( i <= n-1 && ( buffer[i] = getchar() ) != '\n' ) {
i++;
}
if ( i == n ) { /* Note 4 */
buffer[i-1] = '\0';
return -1;
}
else { /* Note 5 */
buffer[i] = '\0';
return 0;
}
}