表达式求值

一个字符串只由'+','-',和‘0’-‘9’组成,并且'+','-'只作为二元运算符。下面算法在vc++6.0中测试通过。

#include<iostream>
#include<string>
#include<list>

using namespace std;

list<char> v1;//符号栈
list<int> v2;//数字栈
int calculate(char *str)
{
 int result = 0;//存放运算结果
 int t1 = 0;
 int t2 = 0;
 int t = 0;//连续的数字需要处理为正整数
 char c;
 while(*str != '\0')
 {
  if(*str >= '0' && *str <= '9')
  {
   t = 10 * t + (*str - 48);
  }
  else if(*str == '+' || *str == '-')
  {
   if(t != 0)//在遇到符号的时候需要将前面的数字压栈
   {
    v2.push_back(t);
    t = 0;
   }
   if(v2.size() == 2)//数字栈中有两个数字,可以进行运算
   {
    c = v1.back();
    t1 = v2.back();
    v2.pop_back();
    t2 = v2.back();
    v2.pop_back();
    if(c == '+')
    {
     result = t1 + t2;
    }
    else if(c == '-')
    {
     result = t2 - t1;
    }
    v1.pop_back();
    v2.push_back(result);
    t1 = 0;
    t2 = 0;
    t = 0;
   }
   v1.push_back(*str);
  }
  str++;
 }
 c = v1.back();
 t1 = v2.back();
 if(c == '+')
 {
  result = t1 + t; 
 }
 else if(c == '-')
 {
  result = t1 - t;
 }
 return result;
}

void main()
{
 char *str = "32+40-52+63";
 int result = calculate(str);
 cout<<result<<endl;
}

posted @ 2013-11-12 14:22  c plus plus  阅读(128)  评论(0)    收藏  举报