- 17
- 0
题目描述
as written, getint treats a + or - not followed by a digit as a valid representation of zero. fix it to push such a character back on th input.
题目来源及自己的思路
来自K-R
相关代码
#include<ctype.h>
#include<stdio.h>
#define SIZE 100
int getch(void);
void ungetch(int c);
/* getint : get next integer from input into *pn */
int getint(int *pn)
{
int c,sign=1;
int d;
while(isspace(c = getch())) /*skip space */
;
if(!isdigit(c) && c!=EOF && c!='-' && c!='+')
{
ungetch(c);
return c; /* It is not a integer */
}
sign = (c == '-')? -1: 1;
if(c == '-' || c == '+')
{
d = c;
if(!isdigit(c = getch()))
{
if( c != EOF)
ungetch(c);
ungetch(d);
return d;
}
}
for(*pn = 0; isdigit(c); c =getch())
*pn = 10 * *pn + (c - '0');
*pn *= sign;
if( c != EOF)
ungetch(c);
return c;
}
int main()
{
int n;
int array[SIZE];
int last = 0;
int j;
int getint(int *pn);
for(n = 0; n < SIZE && getint(&array[n]) != EOF; n++)
;
for(last =n ,j = 0; j < last; j++)
printf("%d\t",array[j]);
printf("%d",j);
return 0;
}
#define BUFSIZE 100
int buf[BUFSIZE]; /* buffer */
int bufp = 0;
int getch(void)
{
if( bufp > 0)
return buf[--bufp];
else
return getchar();
}
void ungetch(int c)
{
if(bufp < BUFSIZE)
buf[bufp++] = c;
else
printf("error : too many characters\n");
}
你期待的结果是什么?实际看到的错误信息又是什么?
当我输入:
// - 5
或者
// + 5
以及字母时,程序就会立即停止,请问这是为什么?
if(c == '-' || c == '+')
{
d = c;
if(!isdigit(c = getch()))
{
if( c != EOF)
ungetch(c);
ungetch(d);
return d;
}
}
这部分我觉得逻辑行得通啊?
当输入: + 5
它存储在缓存区的不就是:(空格)+5吗?
我特意在main函数中加了一个变量j来确定调用了多少次getint函数,发现它调用100次,可为有些数组元素没有被赋初值呢?getint函数中不是有这个语句吗?
for(*pn = 0; isdigit(c); c =getch())
*pn = 10 * *pn + (c - '0');
真心求解,希望能得到解答,谢谢!
0
打赏
收藏
点击回答
网站公告
- 扫一扫访问手机版
回答动态

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器更新之后。服务器里面有部分玩家要重新创建角色是怎么回事啊?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题函数计算不同地域的是不能用内网吧?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题ARMS可以创建多个应用嘛?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题在ARMS如何申请加入公测呀?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题前端小程序接入这个arms具体是如何接入监控的,这个init方法在哪里进行添加?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器刚到期,是不是就不能再导出存档了呢?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器的游戏版本不兼容 尝试更新怎么解决?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器服务器升级以后 就链接不上了,怎么办?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器转移以后服务器进不去了,怎么解决?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器修改参数后游戏进入不了,是什么情况?预计能赚取 0积分收益
- 回到顶部
- 回到顶部
