Page 120 - Programming Microcontrollers in C
P. 120
Structures 105
break;
}
The central loop here is the if statement. Its argument executes
getch() to read in characters from the input stream. These inputs
are converted to lower case and stored into the array location pointed
to by w. The result is then checked to determine if it is a letter or a
number. If it is not, it is put back onto the input stream and the loop
is exited by the break instruction. If it is a letter or a number, the
pointer to the output array w is incremented and the maximum length
of the array is decremented. If this last result is greater than zero, the
next character is read in. Otherwise, the if statement is skipped.
The last two statements in the function are
*w=‘\0’;
return word[0];
The last entry of the character array is made a ’\0’ to satisfy the
C requirement that a string must terminate with a 0, and the first
character of the word is returned to the calling program. This value
is returned just to guarantee that an EOF is not returned.
There are two final functions required for this program. These func
tions work together to form the getch()/ungetch() pair. A global
buffer with an argument BUFSIZE is created, and a global integer
bufp is declared. bufp is initialized to 0. Since these variables are
global, they are initialized at the beginning of the program, and they
will not be changed when control is returned to a calling function.
In getch(), the value of bufp is tested. If it is greater than 0,
the character returned is taken from the buffer and the bufp is
decremented. Otherwise, a new character is read from the input stream
by getchar().
#define BUFSIZE 100
char buf[BUFSIZE]; /* buffer for ungetch */
int bufp=0; /* next free position in buffer */
int getch(void)/* get the next character from the
buffer */