程序应该读取由数字和运算符组成的后缀表达式并计算结果。我尝试使用string
,但我不断得到一个结果。你能告诉我我做错了吗?
#include <iostream>
#include "StackADT.h"
#include <stack>
using namespace std;
#include <string>;
bool isOperator(string);
int calculate (int, char, int);
void display (int, string, int, int);
int main(){
string expr;
int operand2 = 0;
int operand1 = 0;
string thisOperator;
int value;
int result;
cout << "Evaluates a postfix expression(to Quit)." << endl;
cin >> expr;
//while(expr != "-1")
{
//getline( cin, expr,'\n' );
int exprSize = expr.size();
const int siz = 10;
char expr2[siz];
for (int i = 0; i < expr.length; i++)
{
expr2[i] = expr[i];
}
Stack<int> stack;
int index = 0;
while (index < exprSize){
if (!isOperator(expr[index]) )
{
stack.pushStack(expr[index]);
}
else
{
stack.popStack (operand2);
stack.popStack (operand1);
thisOperator = expr[index];
value = calculate (operand1, thisOperator[index], operand2);
stack.pushStack(value);
}
index++;
}
result = stack.popStack (operand1);
display(operand1, thisOperator, operand2, result );
// cout << "Evaluates a postfix expression(to Quit)." << endl;
// cin >> expr;
}
system("pause");
return 0;
}
void display (int op1, string operat, int op2, int result){
cout << op1 << operat << op2 << " = " << result;
}
bool isOperator(char token )
{
if(token == '-' || token == '+' || token == '*' || token == '/')
return true;
else
return false;
}
int calculate (int op1, char operat, int op2){
switch (operat)
{
case '/': return op1 / op2;
break;
case '+': return op1 + op2;
break;
case '*': return op1 * op2;
break;
case '-': return op1 - op2;
break;
default: cout << "Cant / by zero" << endl;
break;
}
}
我正在努力; exprSize =字符串的长度