This is my very first post in stack overflow, so I hope that I do not step on anyone.
Of course, all materials are welcome and appreciated, but those who are most suited for the answer would really read the book "C Programming Language", 2nd ed.
I just finished coding Exercise 6-4, but I can’t understand anything. Why doesn't the getword () function read EOF until I press Ctrl + D (C code in Arch Linux VM)?
Many of my previous exercises from the book require reading from stdin. One way to do this is through something like
while ((c = getchar()) != EOF) {...}
In this case, I never need to press Ctrl + D. I enter my input, press Enter, the stdin buffer is washed out, and EOF is detected automatically. The getword () function also relies on getchar () on its base, so why does it freeze my program?
The getword () function is called from main ():
while (getword(word, MAX_WORD) != EOF) {
if (isalpha(word[0])) {
root = addtree(root, word);
}
}
The getword () function itself:
int getword(char *word, int lim) {
char *w = word;
int c;
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];
}
I put comments to indicate the point at which I determined that EOF is not readable.
The functions getch () and ungetch () are the same as in the Polish notation calculator from chapter 4 (and this program automatically read EOF by pressing Enter):
#define BUF_SIZE 100
char buf[BUF_SIZE];
int bufp = 0;
int getch(void) {
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c) {
if (bufp >= BUF_SIZE) {
printf("ungetch: too many characters\n");
}
else {
buf[bufp++] = c;
}
}
So far, this is the first program that I have written since the beginning of this book, which requires me to manually enter EOF through Ctrl + D. I just can not understand why.
Significant appreciation for clarification ...