c - 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 不再小于数组的长度,我认为这个例子有一个陷阱,所以任何人都可以给出一些想法?很多谢谢!
解决方案
推荐阅读
- java - 我无法让任何 indexOf() 函数为我编写的这段代码工作
- python - 正则表达式查找除特殊字符之间的所有单词之外的所有单词
- spring-boot - 在春季启动中使用@Onetomany @JoinColumn 进行一对多关联?
- android - BuildConfig定义多次,Gradle Test Build报错
- c++11 - 为自定义地图值多次调用复制构造函数
- rxjs - Rx JS 等待,直到所有订阅者都解决了 Promise
- lua - 写入 .txt 文件,而不重命名第一行
- python - 使用 Python 找出每行中的特定字符数并将其存储在数据框中
- python - 奇数或偶数 -> 重复直到满足条件
- python - 如何在 API 响应 Python 3.6.5 中从 S3 返回 zip 文件?