练习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
- 练习4-11 修改getop函数,使其不必使用ungetch函数。提示:可以使用一个static类型的内部变量解决该问题
- 练习4-10 另一种方法是通过getline函数读入整个输入行,这种情况下可以不使用getch和ungetch函数
- 练习 4-10 另一种方法是通过 getline 函数读入整个输入行,这种情况下可以不使用 getch 与 ungetch 函数
- 子类函数使用父类类型做为参数时,调用该参数的protected变量问题
- 练习4-7 编写一个函数ungets(s),将整个字符串压回到输入中。ungets函数需要使用buf和bufp吗?它能否仅使用ungetch函数
- System提供了一个静态方法arraycopy(),我们可以使用它来实现数组之间的复制。 其函数原型是: public static void arraycopy(Object src, int
- c++ 类 函数内部的 static 类型
- 【c++笔记七】教你使用"const类型的对象、成员函数"和"static类型的成员函数、变量"
- 被调用函数内部的局部变量声明为static类型
- 一个可以不传参数就可以在函数中改变调用者内部的变量数据的函数
- static(c中定义的关键字1、被其修饰者 外部无法使用(相反的都可以使用extern在外部使用) 2、函数局部变量使用成为静态的放入静态池-生存期改变。c++进行了扩充,使它在类中有了特殊作用)
- try函数内部生成的变量如何全局使用?
- static 类型变量和函数
- 使用含static变量的函数时需谨慎
- 【php】php函数中static静态变量的使用
- 函数static变量的线程竞争问题
- Mysql 内部函数的使用
- Mysql 内部函数的使用
- As3嵌入字体
- ios学习路线—Objective-C(通知机制)
- Unity3D游戏制作 Day1-实现角色的移动
- Sublime Text生成html标签快捷键
- Eclipse运行C++问题Launch failed,Binary not found
- 练习4-11 修改getop函数,使其不必使用ungetch函数。提示:可以使用一个static类型的内部变量解决该问题
- VirtualBox 安装 Mac OS 及全屏设置
- 学习使用的PL/0编译器增强版PL/0plusplusCompiler(七)扩展repeat-until
- C++学习写在前面
- Hadoop-2.7.2伪分布式集群搭建
- Spring MVC 3.x 消息转换器
- 关于解决/lib/ld-linux.so.2: bad ELF interpreter:
- swift基础判断网络连接
- Struts2整合Spring