Skip to content

Instantly share code, notes, and snippets.

@cycadacka
Last active April 28, 2021 04:56
Show Gist options
  • Save cycadacka/e2f378b5d7740a0ec1536b3759de164b to your computer and use it in GitHub Desktop.
Save cycadacka/e2f378b5d7740a0ec1536b3759de164b to your computer and use it in GitHub Desktop.
Evaluating an infix expression through postfix conversion
#include <iostream>
#include <stack>
using namespace std;
double Evaluate(string input);
int GetTokenPrecedence(char c);
double ApplyOperator(double a, double b, char op);
int main(int argc, char* argv[])
{
for (int i = 1; i < argc; i++) {
cout << argv[i] << " = " << round(Evaluate(argv[i]) * 10000) / 10000 << endl;
}
}
double Evaluate(string input)
{
stack<double> values;
stack<char> operators;
for (size_t i = 0; i < input.length(); ++i) {
char c = input[i];
if (isspace(c)) { // Token is whitespace - Check out documenation for isspace().
continue;
} else if (isdigit(c) || c == '.') { // Token is a number or a decimal point.
double tempValue = 0;
int tempDecimal = 0;
while ((isdigit(input[i]) || input[i] == '.') && i < input.length()) {
if (input[i] == '.') {
i++;
tempDecimal = 1;
} else if (tempDecimal > 0) {
tempDecimal *= 10;
tempValue += ((double) input[i++] - (double) '0') / tempDecimal;
} else {
tempValue = tempValue * 10 + ((double) input[i++] - (double) '0');
}
}
i--;
values.push(tempValue);
} else if (c == '(') { // Token is an opening parentheses.
operators.push(c);
} else if (c == ')') { // Token is a closing parentheses.
while (operators.top() != '(') {
char op = operators.top();
operators.pop();
double a = values.top();
values.pop();
double b = values.top();
values.pop();
values.push(ApplyOperator(a, b, op));
}
operators.pop();
} else { // Token is an operator.
while (!operators.empty() && GetTokenPrecedence(operators.top()) >= GetTokenPrecedence(c)) {
char op = operators.top();
operators.pop();
double a = values.top();
values.pop();
double b = values.top();
values.pop();
values.push(ApplyOperator(a, b, op));
}
operators.push(c);
}
}
while (!operators.empty()) {
char op = operators.top();
operators.pop();
double a = values.top();
values.pop();
double b = values.top();
values.pop();
values.push(ApplyOperator(a, b, op));
}
return values.top();
}
int GetTokenPrecedence(char c)
{
if (c == '*' || c == '/') {
return 2;
} else if (c == '+' || c == '-') {
return 1;
} else {
return 0;
}
}
double ApplyOperator(double a, double b, char op)
{
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
default:
return 0;
}
}
@cycadacka
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment