Warning: 只支持0-9的加减乘除,测试一下博客园功能
Env: Win7+VS2010
$cl main.cpp
$main.exe (3+(4*8))+((6+7)/5)
348*+67+5/+
Result : 37
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stack>
char buff[1000] = {0};
int count=0;//指向buff中下一个可用的位置
char current;//currentExp所指向的字符
char* currentExp;//指向表达式的指针
void T(void);
void F(void);
void G(void);
void fatal(const char* msg)
{
fprintf(stderr, "%s\n", msg);
exit(-1);
}
void T(void)
{
F();
while(strchr("+-", current) != NULL && current != '\0')
{
char temp = current;
current = *(++currentExp);
F();
buff[count] = temp;
count++;
}
}
void F(void)
{
G();
while(strchr("*/", current) != NULL && current != '\0')
{
char temp = current;
current = *(++currentExp);
G();
buff[count] = temp;
count++;
}
}
void G(void)
{
if (current>='0' && current<='9')
{
buff[count]=current;
count++;
current = *(++currentExp);
}
else if (current == '(')
{
current = *(++currentExp);
T();
if (current != ')') fatal("mismatched parantheses!");
current = *(++currentExp);
}
else
{
fatal("bogus expression!");
}
}
/*********************************************************************
** 中缀表达式转换为后缀表达式
**
**
** T-->F{(+|-)F}
** F-->G{(*|/)G}
** G--> 0-9
** --> (T)
*********************************************************************/
void Infix2Postfix(char* expr)
{
current = *(expr);
T();
buff[999] = '\0';
}
int Calculate()
{
std::stack<int> s;
int sum = 0;
int oper1 = 0, oper2 = 0;
int num = 0;
char c;
while(buff[num])
{
c = buff[num];
if (c>'0' && c<'9')
{
s.push(c-'0');
}
else
{
switch (c)
{
case '+':
oper1 = s.top();
s.pop();
oper2 = s.top();
s.pop();
sum = oper2 + oper1;
s.push(sum);
break;
case '-':
oper1 = s.top();
s.pop();
oper2 = s.top();
s.pop();
sum = oper2 - oper1;
s.push(sum);
break;
case '*':
oper1 = s.top();
s.pop();
oper2 = s.top();
s.pop();
sum = oper2 * oper1;
s.push(sum);
break;
case '/':
oper1 = s.top();
s.pop();
oper2 = s.top();
s.pop();
sum = oper2 / oper1;
s.push(sum);
break;
default:
fatal("error");
exit(1);
break;
}
}
num++;
}
return sum;
}
int main(int argc, char *argv[])
{
if (argc != 2)
{
fprintf(stderr, "usage: %s <expression>\n", argv[0]);
exit(1);
}
currentExp = argv[1];
Infix2Postfix(currentExp);
printf( "%s\n", buff);
printf( "Result : %d\n", Calculate());
return 0;
}