buf 数组永远不会有超过一个元素,因为 getop 的实现。那么,它不能被声明为一个普通的char变量吗?
这是程序的源代码,第 74 - 79 页:
#include <ctype.h>
int getch(void);
void ungetch(int);
/* getop: get next character or numeric operand */
int getop(char s[]) /* we pass s[] to getop to store input */
{
int i, c;
while ((s[0] = c = getch()) == ' ' || c == '\t')
;
s[1] = '\0';
if (!isdigit(c) && c != '.')
return c; /* not a number */
i = 0;
if (isdigit(c)) /* collect integer part */
while (isdigit(s[++i] = c = getch()))
;
if (c == '.') /* collect fraction part */
while (isdigit(s[++i] = c = getch()))
;
s[i] = '\0';
if (c != EOF)
ungetch(c);
return NUMBER;
}
#define BUFSIZE 100
char buf[BUFSIZE]; /* buffer for ungetch */
int bufp = 0;
/* getch: the function which actually gets chars! */
int getch(void) /* get a (possibly pushed-back) character */
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c) /* push character back in input */
{
if (bufp >= BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
}
最佳答案
在讨论 getop()
之后的几段中,这本书对 ungetch()
的实现有这样的说法(强调已添加):
The standard library includes a function
ungetch
that provides one character of pushback; we will discuss it in Chapter 7. We have used an array for the pushback, rather than a single character, to illustrate a more general approach.
关于c - K&R 反向抛光计算器中 buf 数组的用途是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20908256/