我有一個很大的問題,從下面的代碼理解幾行ungetch的怪異行爲(註釋中標明的序號):getint模糊的定義,它
首先 - 一個循環的填充數組的代碼輸入數據:
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,爲什麼它不能被調用?這個條件在大部分時間都滿足了,所以我們最終會拒絕每個輸入號碼是多少?
預先感謝回答!
K&R不是學習所有語言花絮的好資源。最好用更詳細的文字或閱讀標準。 – ChiefTwoPencils 2012-08-13 22:34:46