I am currently trying to create a calculator that takes an infix equation and converts it to postfix, then calculates. I've got the calculator to convert when fully parenthesized, but I cannot get the equation to convert it without full parenthesis. I have tried to impliment the conversion as shown below. The only problem is that it crashes, saying that deque iterator isn't dereferencable, when I do not have a deque or iterator in the problem. Any Input is greatly appreciated.
string convert_infix(string infix)
//Accepts an infix expression and converts it to rpn format
{
infix+="!";
const char DECIMAL = '.';
const char LEFT_PARENTHESIS = '(';
stringstream ins (infix);
stringstream outs;
stack<char> operators;
string n_equation;
char operate;
int number;
int prec_in=0, prec_top=1;
if(strchr("+-*/%", ins.peek()) != NULL)
{
switch(ins.peek())
{
case '+': case '-' : prec_in=1;
break;
case '/': case '*': case '%': prec_in=2;
break;
}
switch(operators.top())
{
case '+': case '-' : prec_top=1;
break;
case '/' : case '*': case '%' : prec_top=2;
break;
}
//Loop goes until there is a new line in the istream
while(ins && ins.peek() != '\n')
{
if((isdigit(ins.peek()) || (ins.peek() == DECIMAL)) && ins.peek() != ' ')
{
ins>>number;
numbers.push(number);
}
else
{
if(strchr("+-*/%", ins.peek()) != NULL)
{
operand2=numbers.top();
numbers.pop();
operand1=numbers.top();
numbers.pop();
ins>>operate;
switch(operate)
{
case '+': numbers.push(operand1+operand2);
break;
case '-': numbers.push(operand1-operand2);
break;
case '*': numbers.push(operand1*operand2);
break;
case '/': numbers.push(operand1/operand2);
break;
case '%': numbers.push((int)operand1%(int)operand2);
}
}
else
{
ins.ignore();
}
}
}
return numbers.top();
}
int main ()
{
displayIntro("Derek Krzysiak",__FILE__,"Calculates values and shows them in postfix format");
double result;
string entry;
int i=0;
cout<<"Please enter an expression. Enter ""!"" to end the program."<<endl;
getline(cin,entry);
while(entry!="!")
{
entry=convert_infix(entry);
result=read_and_calc(entry);
cout<<entry<<" = "<<result<<endl;
cout<<"Please enter an expression. Enter ""!"" to end the program."<<endl;
getline(cin,entry);
}