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
/
counter.c
< prev
next >
Wrap
C/C++ Source or Header
|
2005-06-16
|
3KB
|
84 lines
/* counter.c
*
* Synopsis - Reads standard input and keeps a count of the
* number of extra blanks in the input.
*
* Objective - To illustrate a loop to read through many
* lines of input and a method of having a
* function change a pointer parameter.
*/
/* Include Files */
#include <stdio.h>
/* Constant Definitions */
#define BUF_SIZE 512
/* Function Prototypes*/
int countem( char ** ptr ); /* Note 1 */
/* PRECONDITION: *ptr points to a space in a null terminated
* string.
* POSTCONDITION: *ptr points to the first non-space character
* after the initial space. The number of spaces
* found at that location is returned.
*/
int process_line(char *ptr );
/* PRECONDITION: ptr points to the beginning of the buffer
* containing the line to be processed.
* POSTCONDITION: Tne number of "extra" spaces in the processed
* line is returned.
*/
int main( void )
{
char inarray[BUF_SIZE], *inptr; /* Note 2 */
int white_count = 0;
printf( "Enter text. Signal end of file when done.\n" );
printf( "> " );
inptr = fgets( inarray, BUF_SIZE, stdin ); /* Note 3 */
while ( inptr != NULL ) {
/* Note 4 */
white_count += process_line( inptr );
printf( "> " );
inptr = fgets( inarray, BUF_SIZE, stdin ); /* Note 3 */
}
printf( "There were %d unnecessary spaces.\n", white_count );
return 0;
}
/*******************************process_line()*****************/
/* Processes a line of text by looking for blanks, calling
* countem() to count the blanks, and updating the running
* total of the number of blanks.
*/
int process_line( char *ptr )
{
int count;
int extra_whites = 0;
while ( *ptr != '\0' ) {
if ( *ptr == ' ' ) {
count = countem( &ptr ); /* Note 5 */
if ( count >= 2 )
extra_whites += count - 1;
}
else
ptr++;
}
return extra_whites;
}
/*******************************countem()***********************/
int countem( char **ptr ) /* Note 6 */
{
int counter = 0;
while ( **ptr == ' ' ) { /* Note 7 */
counter++;
( *ptr )++; /* Note 8 */
}
return( counter );
}