Mar 8, 2016 at 3:13am UTC
//
//
//
// Copyright © 2016 Suraj Patel . All rights reserved.
//
#include <cstdlib>
#include "stack2.h"
#include<cctype>
#include<iostream>
#include<cstring>
#include <stack>
//evaluates
using namespace std;
double priority(char infix )
{
double temp;
if( infix =='^')
temp = 1;
else
{
if(infix == '*' || infix =='/')
temp = 2;
else
{
if(infix =='+' || infix =='-')
temp = 3;
}
}
return temp;
}
int main(){
string s;
string out;
stack<char>operations;
double i;
cout << "Type a fully parenthesized arithmetic expression : " << endl;
getline(cin, s);
for ( i = 0; i < s.length(); i++) {
if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/' || s[i] == '^') {
while (!operations.empty() && priority(operations.top()) <= priority(s[i])) {
out = operations.top();
operations.pop();
}
operations.push(s[i]);
} else if (s[i] == '(') {
operations.push(s[i]);
} else if (s[i] == ')') {
while (operations.top() != '(') {
out = operations.top();
operations.pop();
}
operations.pop();
} else
{
out = s[i];
}
}
double operand1, operand2, answer = 0;
i = 0;
while (i < s.length())
{
if ( isspace(s[i]) )
{
}
else if ( isdigit( s[i] ))
{
double temp = 0;
do
{
temp = temp*10 + (s[i]-'0');
i++;
if ( i >= s.length())
{
}
} while (isdigit(s[i]));
operations.push(temp);
}
else
{
operand2 = operations.top();
operations.pop();
operand1 = operations.top();
operations.pop();
switch(s[i])
{
case '+': answer=operand1 + operand2;
operations.push(answer);
break;
case '-': answer=operand1 - operand2;
operations.push(answer);
break;
case '*': answer = operand1 * operand2;
operations.push(answer);
break;
case '/': answer=operand1 / operand2;
operations.push(answer);
break;
}
}
i++;
}
cout << "that evaluates : " << answer <<endl;
cin.ignore();
return 0;
}
Mar 8, 2016 at 8:32am UTC
Please use the code tags to format your code.
If you have a question, please ask it.
Mar 8, 2016 at 5:28pm UTC
Sorry, forgot to ask. I need it to change from infix to postfix and evaluate at the same time verse two different times.
Mar 8, 2016 at 6:43pm UTC
I would like to point out you have no reason to make priority a double. You should make it an int.
You are right for using a priority type function though.
I'm not sure if this is your own code but this does have the jyst of a working infix to postfix. Tell me, is this your code? And if it is, do you know it successfully converts infix to postfix?