在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/C/ k&r getint.c 為什么輸入字母或+(空格)5,程序就立即停止了

k&r getint.c 為什么輸入字母或+(空格)5,程序就立即停止了?

題目描述

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.

題目來(lái)源及自己的思路

來(lái)自K-R

相關(guān)代碼

#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");
}

你期待的結(jié)果是什么?實(shí)際看到的錯(cuò)誤信息又是什么?

當(dāng)我輸入:
// - 5
或者
// + 5
以及字母時(shí),程序就會(huì)立即停止,請(qǐng)問(wèn)這是為什么?

if(c == '-' || c == '+')
{
    d = c;
    if(!isdigit(c = getch()))
    {
        if( c != EOF)
            ungetch(c);
        ungetch(d);
        return d;
    }    
}

這部分我覺(jué)得邏輯行得通?。?br>當(dāng)輸入: + 5
它存儲(chǔ)在緩存區(qū)的不就是:(空格)+5嗎?
我特意在main函數(shù)中加了一個(gè)變量j來(lái)確定調(diào)用了多少次getint函數(shù),發(fā)現(xiàn)它調(diào)用100次,可為有些數(shù)組元素沒(méi)有被賦初值呢?getint函數(shù)中不是有這個(gè)語(yǔ)句嗎?

for(*pn = 0; isdigit(c); c =getch())
        *pn = 10 * *pn + (c - '0');

真心求解,希望能得到解答,謝謝!

回答
編輯回答
蔚藍(lán)色

我copy,編譯運(yùn)行了,可以正常運(yùn)行啊。。
不過(guò)你這程序?qū)懙摹?。。。。。有點(diǎn)搞笑2333

2017年4月28日 23:10
編輯回答
帥到炸
本來(lái)想繼續(xù)追問(wèn)的,我一步一步地寫(xiě)下來(lái)(就是下面的),然后。。。。。
比如:當(dāng)輸入+(空格)5(再按enter)的時(shí)候,在getint函數(shù)中,不是先c='+';**然后isspace()不成立,然后下面這個(gè)if條件不成立,然后sign=1;然后下的if條件成立,然后 d=c; 然后 c=' '; 然后因?yàn)榭崭癫皇菙?shù)字并且不等于EOF ,ungetch(c),空格先存進(jìn)緩存區(qū),然后ungetch(d),'+'存進(jìn)緩存區(qū);并且return c;返回 '+' 給main,'+' != EOF,繼續(xù)循環(huán);調(diào)用getint函數(shù),c=getch()令c='+';**然又是這樣(加粗的),main里的while循環(huán)SIZE遍,但數(shù)組array再也沒(méi)有被賦值,所以有很數(shù)組元素的值是隨機(jī)素。
輸入字母之類(lèi)的也是一樣的。
2017年12月29日 20:52