练习4-11 修改getop函数,使其不必使用ungetch函数。提示:可以使用一个static类型的内部变量解决该问题

来源:互联网 发布:手机人工智能有什么用 编辑:程序博客网 时间:2024/05/19 02:22

用一个static变量存储多读取的字符,static变量一直存在,在调用getop函数结束后不会消失。在再次调用getop开始,将其赋值给c,但最开始时没有多读取字符,不需要从变量开始,变量初始化,若等于初始值,则说明是最开始。

#include <stdio.h>#include <stdlib.h>#define MAXOP 100#define NUMBER '0'int getop(char []);void push(double);double pop(void);main(){    int type;    double op2;    char s[MAXOP];    while((type=getop(s))!=EOF){        switch(type){        case NUMBER:            push(atof(s));            break;        case '+':            push(pop()+pop());            break;        case '*':            push(pop()*pop());            break;        case '-':            op2=pop();            push(pop()-op2);            break;        case '/':            op2=pop();            if(op2!=0.0)                push(pop()/op2);            else                printf("error: zero divisor\n");            break;        case '\n':            printf("\t%.8g\n",pop());            break;        default:            printf("error: unknown command %s\n",s);            break;        }    }    return 0;}#define MAXVAL 100int sp=0;double val[MAXVAL];void push(double f){    if(sp<MAXVAL)        val[sp++]=f;    else        printf("error: stack full,can't push %g\n",f);}double pop(void){    if(sp>0)        return val[--sp];    else{        printf("error: stack empty\n");        return 0.0;    }}#include <ctype.h>int getch(void);void ungetch(int);int bufp=0;int getop(char s[]){    int i,c;    static int tempt=0;    if(tempt==0)        c=getch();    else    {        c=tempt;        tempt=0;    }    while((s[0]=c)==' '||c=='\t')        c=getch();    s[1]='\0';    if(!isdigit(c)&&c!='.')        return c;    i=0;    if(isdigit(c))        while(isdigit(s[++i]=c=getch()))        ;    if(c=='.')        while(isdigit(s[++i]=c=getch()))        ;    s[i]='\0';    if(c!=EOF)        tempt=c;    return NUMBER;}#define BUFSIZE 100char buf[BUFSIZE];int getch(void){    return (bufp>0)? buf[--bufp]:getchar();}void ungetch(int c){    if(bufp>=BUFSIZE)        printf("ungetch: too many characters\n");    else        buf[bufp++]=c;}

ungetch函数没用到,getch函数都不用,直接用getchar即可。

    else    {        c=tempt;        tempt=0;    }

保证再次计算时tempt等于初始值。

0 0
原创粉丝点击