gpt4 book ai didi

c - 关于 K&R C 中 getop() 的查询

转载 作者:太空宇宙 更新时间:2023-11-03 23:25:50 31 4
gpt4 key购买 nike

在下面的函数中:

  1. 为什么它最初以 s[1] = '\0'; 终止字符串?
  2. i = 0 之后,为什么开始从 s[1] 而不是 s[0] 取值?
#define NUMBER '0'
#define MAXSIZE 100
char s[MAXSIZE];

/* getop: get next character or numeric operand */

int getop(char s[ ])
{
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;
}

最佳答案

  1. 该函数似乎将其结果存储在一个指向字符串 的指针中,以 C 风格零终止。第一行 getch 将其结果存储在 s[0] 中,如果不是数字或句点,则立即返回。将零存储为第二个字符可确保返回的字符串正确结束——它仅包含一个字符。

  2. 在初始步骤之后,您已经有了一个有效字符,它存储在 s[0] 中。因此,所有接下来的 getch 调用都需要从 1 开始存储,否则它会覆盖输入的第一个字符。

关于c - 关于 K&R C 中 getop() 的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27647389/

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