gpt4 book ai didi

c - k&r 中的 getint 模糊定义,其中 ungetch 的奇怪行为

转载 作者:行者123 更新时间:2023-11-30 15:55:36 28 4
gpt4 key购买 nike

我在理解以下代码中的几行(注释中标记的数字)时遇到了很大的问题:

首先 - 用输入数据填充数组的循环代码:

int n, array[SIZE], getint(int *);
for (n = 0; n < SIZE && getint(&array[n]) != EOF; n++)
;

现在是函数定义:

/* getint:  get next integer from input into *pn */

int getint(int *pn)

{

int c, sign;

while (isspace(c = getch())) /* skip white space */
;

if (!isdigit(c) && c != EOF && c != '+' && c != '-') {
ungetch(c); /* [1] */ /* it is not a number */
return 0; /* [2] */
}
sign = (c == '-') ? -1 : 1;
if (c == '+' || c == '-')
c = getch();
for (*pn = 0; isdigit(c); c = getch())
*pn = 10 * *pn + (c - '0'); [3]
*pn *= sign;
if (c != EOF) /* [4a] */
ungetch(c); /* [4b] */
return c;
}



#define BUFSIZE 100

char buf[BUFSIZE]; /* buffer for ungetch */
int bufp = 0; /* next free position in buf */

int getch(void) /* get a (possibly pushed-back) character */
{
return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c) /* push character back on input */
{
if(bufp >= BUFSIZE)
printf(" ungetch too many characters\n");

else
buf[bufp++] = c;
}

所以:

[1] 我在这里读过类似的帖子,收回这样一个不需要的字符会以某种方式阻塞缓冲区,因此我们需要使用另一个函数清除它。对我来说,奇怪的是它没有包含在 K&R 中,而且作者甚至没有提到使用它的必要性?

[2] 为什么我们返回 0?这会停止整个 main() 程序吗?或者只是将 0 放入数组中? ( getint(&array[n] ) ?

[3] 为什么我们需要实现这样一个公式来计算“大数”?因为该函数只是一个接一个地获取数字(getchar 而不是 getword),然后通过几个单个整数创建“大数字”。

[4a][4b] 如果 c != EOF 为什么它会被取消?这个条件大多数时候都满足,所以我们最终会拒绝每个输入的数字?

提前感谢您的回答!

最佳答案

  1. 它不会,即使它与其他一些库一起使用,但不会与这两个函数一起使用
  2. 不。它只是返回零并保留整数未初始化(这种情况不在循环中处理)
  3. 你什么意思?这就是根据数字计算整数的简单方法。
  4. 它将简单地ungetch函数刚刚读取和处理的整数后面的字符 - 除非没有字符但有EOF标记的流结尾。该标记不会返回到缓冲区。

关于c - k&r 中的 getint 模糊定义,其中 ungetch 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11942968/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com