这是书中P109页的示例源码,修改了getchar输入方式,而是提前放在一个字符串中,程序只能处理一位的数字字符串,源码:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char token;
int exp();
int term();
int factor();
void err()
{
printf("Err\n");
exit(1);
}
char strExp[100] = "5+(8+2)-4*5+(9-8+2)*6"; //要计算的表达式
static int c = 0; //当前要获取的字符下标
char GetNextChar()
{
return strExp[c++];
}
char GetPreChar()
{
c--;
if (c<=0)
{
c = 0;
}
return strExp[c];
}
void match(char exceptedToken)
{
if (token == exceptedToken)
{
token = GetNextChar();
}
else
{
err();
}
}
int exp()
{
int temp = term();
while((token == '+') || (token == '-'))
{
switch(token)
{
case '+':
match('+');
temp += term();
break;
case '-':
match('-');
temp -= term();
break;
}
}
return temp;
}
int term()
{
int temp = factor();
while(token == '*')
{
match('*');
temp *= factor();
}
return temp;
}
int factor()
{
int temp;
if (token == '(')
{
match('(');
temp = exp();
match(')');
}
else if (isdigit(token))
{
//ungetc(token, stdin);
//token = GetPreChar();
//scanf("%d", &temp);
char str[10] = {0};
str[0] = token;
temp = atoi(str); //只能处理一位的数字字符串
token = GetNextChar();
}
else
{
err();
}
return temp;
}
void main()
{
int ret;
token = GetNextChar();
ret = exp();
if (token == '\0') //由'\n'换成了'\0'
{
printf("结果 = %d\n", ret);
}
else
{
err();
}
}