Hi!
Below I am posting three functions: one getword(), and two
supporting ones getch() and ungetch().
I have issues with understanding the code.
Please, help me to get through it.
The word to use as an example: hello (as usually done).
1) the first while loop skips through all space characters; and stops
when getch() returns a non-space character; so at the end of the loop
c = some non-space character, if there were characters considered as
spaces at the beginning of the word.
Code:
while (isspace(c = getch ()))
;
not relevant to the input "hello"
2) if statement checks if c = EOF; if not, then w[0] = c, and
*w is incremented to point to w[1].
Code:
if (c != EOF)
{
*w++ = c;
}
So, w[0] = 'h'
3) next if statement checks if that c is alphabetical character; if it
is not, then the word ends by assigning '\o' to w[1];
not the case for hello.
Code:
if (!isalpha(c))
{
*w = '\0';
return c;
}
4) for loop begins from w[1] (because w[0] = c), and it iterates
until lim = 1, incrementing *w with each iteration, and with each iteration it prompts for the input by *w = getch().
The inner
Code:
if (isalnum(*w = getch()))
statement checks
if *w (after it is assigned value it gets from getch) is alphanumeric.
This part I don't understand:
it says, that if *w value is alphanumeric, ungetch() (put into buffer)
and break. Does it mean that even if there are alphabetic characters
in the input, the program will ungetch them and not assign to the
next *w? I understand I am wrong, but I read this if statement as the one that would eliminate the possibility of filling in the given array
with alphabetical characters.
What is my mistake?
Code:
for ( ; --lim > 0; w++)
{
if (isalnum(*w = getch()))
{
ungetch(*w);
break;
}
Here are all 3 functions:
Code:
/* GETCH and UNGETCH functions */
#define BUFSIZE 100
/* buffer for ungetch */
static char buf[BUFSIZE];
/* next free position in buf */
static int bufp = 0;
/* get a (possibly pushed back) character */
int getch (void)
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
/* push character back on input */
void ungetch (int c)
{
if (bufp >= BUFSIZE)
{
printf("ungetch: too many characters\n");
}
else
{
buf[bufp++] = c;
}
}
/* getword: get next word or characer from input */
int getword (char *word, int lim)
{
int c, getch(void);
void ungetch(int);
char *w = word;
while (isspace(c = getch ()))
;
if (c != EOF)
{
*w++ = c;
}
if (!isalpha(c))
{
*w = '\0';
return c;
}
for ( ; --lim > 0; w++)
{
if (isalnum(*w = getch()))
{
ungetch(*w);
break;
}
}
*w = '\0';
return word[0];
}
Thanks!