账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    k&r getint.c 为什么输入字母或+(空格)5,程序就立即停止了?
    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
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部