什么是与ungetc(或ungetch从K&安培; R)的目的是什么? [英] What is the purpose of ungetc (or ungetch from K&R)?

查看:191
本文介绍了什么是与ungetc(或ungetch从K&安培; R)的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以向我解释ungetch的目的是什么?
这是K&安培;其中创建逆波兰计算器R第4。

Can anyone explain to me the purpose of ungetch? This is from K&R chapter 4 where you create a Reverse Polish Calculator.

我已经运行该程序,而不调用ungetch和我的测试中它仍然有效一样。

I've ran the program without the call to ungetch and in my tests it still works the same.

 int getch(void) /* get a (possibly pushed back) character */
    {
        if (bufp > 0)
        {
            return buf[--bufp];
        }
        else
        {
            return getchar();
        }
    }

    void ungetch(int c) /* push character back on input */
    {
        if (bufp >= BUFSIZE)
        {
            printf("ungetch: too many characters\n");
        }
        else
        {
            buf[bufp++] = c;
        }

}

(我已经删除了残培三元运算符使其更清晰。)

(I've removed the ternary operator in getch to make it clearer.)

推荐答案

我不知道你指的是具体的例子(这是probaby23年,因为我读K&安培; R,这是第一个版本。 ),但往往解析它的方便,窥视下一个字符,看它是否是你目前正在解析哪个部分的时候。举例来说,如果你读了您要继续阅读的数字,直到你来到一个非数字。与ungetc让读者人数看看下一个字符不消耗它,以便其他人可以读取它。在3 + 2格雷格Hewgill的例子中,读者数量会读3位,然后读的加号和识数完毕后,再与ungetc加号,以便以后可以读取。

I don't know about the specific example you're referring to (It's probaby 23 years since I read K&R, and that was the first edition.), but often when parsing it's convenient to 'peek' at the next character to see if it is part of what you're currently parsing. For instance, if you're reading a number you want to keep reading digits until you come to a non-digit. Ungetc lets the number reader look at the next character without consuming it so that someone else can read it. In Greg Hewgill's example of "2 3+", the number reader would read the 3 digit, then read the plus sign and know the number is finished, then ungetc the plus sign so that it can be read later.

这篇关于什么是与ungetc(或ungetch从K&安培; R)的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆