首页 > 解决方案 > K&R c 书籍第 5.2 节 getint 示例

问题描述

在第 5.2 节 getint 示例中,我得到了一些不寻常的东西,不容易理解,还有一些问题

#include <stdio.h>
#include <ctype.h>
#define SIZE 5
#define BUFSIZE 100
char buf[BUFSIZE];
int sp = 0;
int getch(void);
void ungetch(int);
int main(){
    int n, array[SIZE],getint(int *);
    for (n = 0; n < SIZE && getint(&array[n]) != EOF; n++)
            printf("the %d index is %d\n", n, array[n]);
    //int i;
    //for (i = 0 ; i < n; i++)
    //    printf("the %d index is %d\n", i, array[i]);
}
int getint(int *pn){
   int c, sign;
   while(isspace(c = getch()))/* skip white space  */
           ;
   if (!isdigit(c) && c != EOF && c != '+' && c != '-'){
       ungetch(c);
       return 0;
   }
   sign = (c == '-')? -1:1;
   if (c == '+' || c == '-'){
       c = getch();
   }
   for (*pn = 0; isdigit(c); c = getch())
       *pn = 10 * *pn + (c - '0');
   *pn *= sign;
   if (c != EOF)
       ungetch(c);
   return c;
}
int getch(){
    return (sp > 0)? buf[--sp]:getchar();
}
void ungetch(int s){
    buf[sp++] = s;
}

我用 cc 编译它,然后运行它:当我输入以下内容时:

& ( * ^

我得到了结果:

the 0 index is 594377088
the 1 index is 21914
the 2 index is 594376288
the 3 index is 21914
the 4 index is -91537120

这完全是一个毫无意义的结果;

而以下一个:

897 647 908 223 456

我得到了预期的结果:

the 0 index is 897
the 1 index is 647
the 2 index is 908
the 3 index is 223
the 4 index is 456

我认为有几点值得讨论:从书中说 getint 将返回 EOF 作为文件结尾,0 表示不是数字,正值表示有效数字,但是当我输入 * & $ 时,这不是number,它会遇到 ungetch(c) 并返回 0,直到 n 不再小于数组的长度,我认为这个例子有一个陷阱,所以任何人都可以给出一些想法?很多谢谢!

标签: cpointers

解决方案


推荐阅读