首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用getch()读取负数

使用getch()读取负数
EN

Stack Overflow用户
提问于 2011-03-30 06:20:28
回答 1查看 1.3K关注 0票数 1

所以我正在学习C编程语言这本书。解决计算器的问题。它要求添加对负数的支持;我这样做了,但我发现了一种奇怪的行为,我无法解释。

代码语言:javascript
复制
int getop(char s[])
{
    int i = 0, c, next;
    /* Skip whitespace */
    while((s[0] = c = getch()) == ' ' || c == '\t')
        ;
    s[1] = '\0';    
    /* Not a number but may contain a unary minus. */
    if(!isdigit(c) && c != '.' && c != '-')
        return c;
    if(c == '-')
    {
        next = getch();
        if(!isdigit(next) && next != '.')
           return c;
        c = next;
    }
    else
        c = getch();    

    while(isdigit(s[++i] = c)) //HERE
            c = getch();
    if(c == '.')                     /* Collect fraction part. */
        while(isdigit(s[++i] = c = getch()))
                        ;
    s[i] = '\0';
    if(c != EOF)
        ungetch(c);
    return NUMBER;
}

适用于正数和负数

代码语言:javascript
复制
int getop(char s[])
{
    ...

    while(isdigit(s[++i] = c = getch())) //HERE
            ;
    if(c == '.')                     /* Collect fraction part. */
        while(isdigit(s[++i] = c = getch()))
                        ;
    s[i] = '\0';
    if(c != EOF)
        ungetch(c);
    return NUMBER;
}

仅适用于正数。

为什么!?

getch()

代码语言:javascript
复制
char buf[BUFSIZE]; /* buffer for ungetch */
int bufp = 0; /* next free position in buf */    
int getch(void) /* get a (possibly pushed-back) character */    {
    return (bufp > 0) ? buf[--bufp] : getchar();
}

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-03-30 06:24:51

代码语言:javascript
复制
while(isdigit(s[++i] = c))
    c = getch();

代码语言:javascript
复制
while(isdigit(s[++i] = c = getch()))
    ;

有不同的行为。后者在进入循环之前读取一次,并检查读取的值是否为数字,而前者检查先前读取的值是否为数字。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5479630

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档