/*
不带括号的表达式的四则运算
使用两个堆栈,一个op(存放加号与减号)
一个exp(存放操作数)
乘除法直接计算,加减法先压入堆栈
*/
#include <string>
#include <iostream>
#include <stack>
#include <cctype>
#define maxInt 65535
using namespace std;
stack<char> op; //存放操作符
stack<int> exp;//存放操作数
int add(int num1,int num2)
{
return num1 + num2;
}
int minus(int num1,int num2)
{
return num1 - num2;
}
int mutiple(int num1,int num2)
{
return num1 * num2;
}
int devide(int num1,int num2)
{
return num1 / num2;
}
/*
将字符转化成数字,并且修正当前的索引cur
*/
bool convertToNumber(int &cur,int &num,char * str)
{
num = 0;
if(strlen(str) <= 0)
return false;
if(!isdigit(str[cur]))
return false;
while(isdigit(str[cur]))
{
num = num * 10 + str[cur] - '0';
if(num > maxInt)//溢出
return false;
cur ++;
}
return true;
}
bool calc(char * str,int & res)
{
int strLen = strlen(str) ;
if(strLen<= 0)
return false;
int cur = 0;
if(!isdigit(str[cur]))
{
cout << "error char"<<endl;
return false;
}
while(cur < strLen)
{
if(isdigit(str[cur]))//转化数字,压入exp栈中
{
int num = 0;
if(!convertToNumber(cur,num,str))
{
cout <<"error" << endl;
return false;
}
exp.push(num);
continue;
}
else
{
switch(str[cur])
{
case '+' : //如果是加号和减号则压入op
case '-' :
{
op.push(str[cur]);
cur ++;
break;
}
case '/'://如果是乘法与和除法,弹exp栈,取一个数字计算结果,并将结果压入exp
{
int num;
cur ++ ;
if(convertToNumber(cur,num,str))
{
int res = devide(exp.top(),num);
exp.pop();
exp.push(res);
break;
}
else
{
cout << "error" <<endl;
return false;
}
}
case '*':
{
int num;
cur ++;
if(convertToNumber(cur,num,str))
{
int res = mutiple(exp.top(),num);
exp.pop();
exp.push(res);
break;
}
else
{
cout << "error" <<endl;
return false;
}
}
default:
{
cout << "error char" <<endl;
}
}
}
}
while(!op.empty())
{
if(exp.empty())
{
cout << "error " <<endl;
return false;
}
if(op.top() == '+')
{
int n1 = exp.top();
exp.pop();
int n2 = exp.top();
exp.pop();
exp.push(add(n1,n2));
}
else if(op.top() == '-')
{
int n1 = exp.top();
exp.pop();
int n2 = exp.top();
exp.pop();
exp.push(minus(n1,n2));
}
else
{
cout << "error char "<< endl;
return false;
}
op.pop();
}
if(exp.size() == 1)
{
res = exp.top();
exp.pop();
return true;
}
else
return false;
}
int main()
{
char str[500];
freopen("in.txt","r",stdin);
int result = 0;
cin>>str;
calc(str,result);
cout << result <<endl;
fclose(stdin);
return 0;
}
异常情况处理好麻烦啊。。。

1378

被折叠的 条评论
为什么被折叠?



