我正在学习K&R书。目前我正在阅读第78页上的getop()函数。 我理解了代码,但我需要澄清两件事。
getop()函数的代码如下:
int getch(void);
void ungetch(int);
/* 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;
}
我的问题是关于:s[0]
在以下代码中的含义:
while ((s[0] = c = getch()) == ' ' || c == '\t')
while ((c = getchar()) == ' ' || c == '\t') ;
while循环的想法是跳过空格和横向制表符,那么为什么我们要将'c'保存在s[0]中呢?为什么作者们不直接写如下代码:
while ((getchar()) == ' ' || c == '\t') ;
while (c= getch() == ' ' || c == '\t')
之后我们将不再使用空格和制表符,那么为什么需要将 c 保存在 s[0]
中?这里需要 s[0]
的原因是什么?
我的第二个问题是关于:
s[1] = '\0';
为什么在这里将'\0'(字符串结束符)分配给s[1]?我已经阅读了stackoverflow.com上关于它的一些先前答案,但我还不完全相信!关于上述问题的被接受答案是:“因为函数可能在剩余输入被读取之前返回,然后s需要是一个完整(并且终止的)字符串。”好的。但是如果输入以一个空格开头,然后跟着一个操作数或操作符呢?在这种情况下,s[1]='\0'会过早地关闭字符串吗?难道不是吗?