【发布时间】:2014-01-03 16:28:59
【问题描述】:
由于 getop 的实现,buf 数组永远不会有多个元素。那么,不能将其声明为普通的 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中的声明while ((s[0] = c = getch())将暗示buf可能包含多个字符。这无法从显示的有限代码示例中确定。如果确实只有一个字符被放入buf,那么,当然,你只需要一个char。但我怀疑你误解了其余的代码。 -
ungetchar() 在 getop 中只使用一次,因此每次函数调用只能上传到缓冲区一个字符。
-
这只是
ungetchar在特定情况下使用。缓冲区也可以从其他地方加载,在您显示的任何代码中都没有显示。我怀疑uncgetch是通常加载缓冲区的机制。它更像是一个实用功能来“撤消”先前的getch。您需要查看第 74-79 页上的所有代码,并查看buf的使用位置。 -
这里是完整的源代码:pastebin.com/jXGp0aKx,看来buf只在getch和ungetch内部使用。
-
谢谢。
ungetch在getop的末尾附近被调用。是否有可能在调用getch之前多次调用它?
标签: c arrays char kernighan-and-ritchie