I started with my own implementation of an algebraic calculator but ran into issues very early into the process. Then, I implemented the algorithm here. Please provide some inputs on areas where I can improve.
#include <iostream>
#include <stack>
#include <string>
#include <algorithm>
class infixProcessor{
public:
infixProcessor(std::string input){
inputString = input;
}
private:
std::string inputString;
std::string postfixExpr;
std::stack<char> stk;
std::stack<std::string> postStk;
bool isNumber (char inputValue){
if (inputValue >=48 && inputValue <= 57) return true;
else return false;
}
bool isOpenParen(char inputValue){
if (inputValue == '(') return true;
else return false;
}
bool isCloseParen(char inputValue){
if (inputValue == ')') return true;
else return false;
}
bool isOperator(char inputValue){
if (inputValue == '+' || inputValue == '-') return true;
else return false;
}
bool isSpace(char inputValue){
if (inputValue == ' ') return true;
else return false;
}
public:
void process(){
inputString.erase(std::remove(inputString.begin(),inputString.end(),' '),inputString.end());
std::string::iterator strIt;
for (strIt = inputString.begin() ; strIt != inputString.end() ; strIt++){
char currentValue = *strIt;
if (isNumber(currentValue)){
postfixExpr += currentValue;
//Peek ahead, if next character is part of previous number
while ( isNumber(*(strIt+1)) ){
postfixExpr += *(strIt+1);
strIt++;
}
postfixExpr += ' ';
}
else if (isOperator(currentValue)){
while ( !stk.empty() && isOperator(stk.top()) ){
postfixExpr += stk.top();
postfixExpr += ' ';
stk.pop();
}
stk.push(currentValue);
}
else if (isOpenParen(currentValue)){
stk.push(currentValue);
}
else if (isCloseParen(currentValue)){
char temp = stk.top();
stk.pop();
while ( !isOpenParen(temp) ){
postfixExpr += temp;
postfixExpr += ' ';
temp = stk.top();
stk.pop();
}
}
}
while ( !stk.empty() ){
char temp = stk.top();
postfixExpr += temp;
postfixExpr += ' ';
stk.pop();
}
}
private:
int makeCalc(std::string num1, std::string num2, char op){
if (op == '+') {
return (std::stoi(num2) + std::stoi(num1));
}
else if (op == '-'){
return (std::stoi(num2) - std::stoi(num1));
}
}
public:
int postfixProcess(){
std::string::iterator strIt;
for (strIt = postfixExpr.begin() ; strIt != postfixExpr.end(); strIt++){
char currentValue = *(strIt);
if (isSpace(currentValue)) continue;
else if (isNumber(currentValue)){
std::string toPush;
toPush += currentValue;
while( isNumber(*(strIt+1)) ){
toPush+=*(strIt+1);
strIt++;
}
postStk.push(toPush);
}
else if (isOperator(currentValue)){
std::string num1, num2;
num1 = postStk.top();
postStk.pop();
num2 = postStk.top();
postStk.pop();
int result = makeCalc(num1, num2, currentValue);
postStk.push(std::to_string(result));
}
}
return std::stoi(postStk.top());
}
};
int main(){
infixProcessor myProcessor("(1+(4+5+2)-3)+(6+8)");
myProcessor.process();
std::cout << myProcessor.postfixProcess() << std::endl;
return 0;
}