| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 4555 人关注过本帖
标题:在书上看到 getint()函数的代码,对其中的 getch,ungetch 十分不解。求帮 ...
取消只看楼主 加入收藏
风雪归人
Rank: 2
等 级:论坛游民
帖 子:7
专家分:10
注 册:2014-11-1
结帖率:0
收藏
已结贴  问题点数:20 回复次数:0 
在书上看到 getint()函数的代码,对其中的 getch,ungetch 十分不解。求帮我解解惑啊!! T.T
getint()函数的要求:接收自由格式的输入,并执行转换,将输入的字符流分解为整数,每次调用得到一个整数。达到结尾时返回文件结尾标志EOF。

书上的代码是这样:
#include <ctype.h>
int getch(void);
void ungetch(int);

int getint(int *pn)
{
    int c, sign;
    while (isspace(c = getch()))
    ;                          //跳过空白
    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);
}

其中ungetch函数大致就是标准库的ungetc,
书上说它是把字符压入回输入中。如果是这样的话,那:
假如我输入 “  xy123”
前面的两个空格会被while (isspace(c = getch())); 屏蔽掉。
这时c=getch(); c的值为x。   
c的值满足if条件(!isdigit(c) && c != EOF && c != '+' && c != '-')
执行ungetch(c)
就把c=x的值压回输入中。
函数结束
因为循环执行函数,下次执行函数时,c=getch();  c不是应该还为x吗?(从ungetch那来的)这启不是无限死循环了??

不解啊,我到底是哪里理解错了
搜索更多相关主题的帖子: include return 
2014-11-26 22:39
快速回复:在书上看到 getint()函数的代码,对其中的 getch,ungetch 十分不解。 ...
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.011121 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved