#include <stdio.h>
#include <stdlib.h>
#define MAXOP 100
#define NUMBER '0'
int getop(char []);
void push(double);
double pop(void);
// 调试的时候输入 12 5 + 4 2 - * 中间用空格隔开,以回车结束
int main(int argc, char *argv[])
{
int type;
double op2;
char s[MAXOP];
while((type=getop(s))!='\n'){
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;
default:
printf("error: unknown command %s\n",s);
break;
}
}
if (type=='\n') printf("\t%.8g\n",pop());
system("pause");
return 0;
}
/******************************************
push && pop
******************************************/
#define MAXVAL 100
int 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;
}
}
/********************************************
getop
********************************************/
#include <ctype.h>
int getch(void);
void ungetch(int);
int getop(char s[])
{
int i,c;
while( (s[0]=c=getch()) ==' ' || c=='\t')
;
s[1]='\0';
if (!isdigit(c) && 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';
/*
原书中用的 != EOF 我为了方便改为 != '\n'
全代码中 唯一这个地方调用了 ungetch , 但是我把下面
这行注释掉程序也能运行,结果不会出错
那 为什么要设计 ungetch 函数?
*/
if (c!='\n') ungetch(c);
return NUMBER;
}
/********************************************
getch && ungetch
********************************************/
#define BUFSIZE 100
char buf[BUFSIZE];
int bufp=0;
int getch(void)
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c)
{
if (bufp>=BUFSIZE)
printf("error in ungetch: too many characters\n");
else
buf[bufp++]=c;
}
the c programming language 第四章 的一个例子.
注:小知识点.
1. getchar() 和 getch() 的区别
getchar: Reads a character from standard input.
getch : Gets a character from the console without echo.
两者的区别是: getch()函数不将读入的字符回显在显示屏幕上, getchar()函数等待输入直到按回车才结束, 回车前的所有输入字
符都会逐个显示在屏幕上。但只有第一个字符作为函数的返回值。
2.ungetch : Pushes back the last character read from the console.
#include <conio.h>
#include <ctype.h>
#include <stdio.h>
int main( void )
{
char buffer[100];
int count = 0;
int ch;
ch = _getche();
while( isspace( ch ) ) // Skip preceding white space.
ch = _getche();
while( count < 99 ) // Gather token.
{
if( isspace( ch ) ) // End of token.
break;
buffer[count++] = (char)ch;
ch = _getche();
}
_ungetch( ch ); // Put back delimiter.
buffer[count] = '\0'; // Null terminate the token.
printf( "\ntoken = %s\n", buffer );
}