Hello
I have been trying too long for this but I think I am gonna ask for help.
#include<iostream>
#include<string>
#include<math.h>
#include "numStack.h"
#include"charStack.h"
using namespace std;
int getNum(int num[],int count);
int addition(int n1,int n2);
int subtraction(int n1, int n2);
int multiplication(int n1,int n2);
int division(int n1, int n2);
int main(){
string str;
int stackSize = 0;
cout<<"Please enter infix line: ";
getline(cin,str);
stackSize = str.length();
int num[50]={0};
int pushNum = 0;
int popNum1 = 0;
int popNum2 = 0;
char popChar = NULL;
int popResult = 0;
int j=0;
numStack intStack(stackSize);
charStack opStack(stackSize);
for(int i=0;i<stackSize;i++){
if(str[i] >= '0' && str[i] <= '9' ){
num[j] = (str[i]-'0');
j=j+1;
}
else if(str[i] == '+' || str[i] == '-' ||
str[i] == '*' || str[i] == '/' ){
pushNum = getNum(num,j);
if((intStack.peek())!=pushNum || pushNum <= 0 ){
intStack.push(pushNum);
j=0;
}
opStack.push(str[i]);
}
else if(str[i] == ')'){
pushNum = getNum(num,j);
if((intStack.peek())!=pushNum || pushNum<=0 ){
intStack.push(pushNum);
j=0;
}
else ;
intStack.pop(popNum1);
intStack.pop(popNum2);
opStack.pop(popChar);
if(popChar == '+'){intStack.push(addition(popNum1,popNum2));}
else if(popChar == '-'){intStack.push(subtraction(popNum1,popNum2));}
else if(popChar == '*'){intStack.push(multiplication(popNum1,popNum2));}
else {intStack.push(division(popNum1,popNum2));}
}
else;
}
intStack.pop(popResult);
cout<<popResult<<endl;
return 0;
}
int getNum(int num[],int count){
int calNum = 0;
int l = 0;
for( int k = count -1 ; k >= 0 ; k--){
calNum = calNum + (num[l] * int(pow(10.0,(k))));
l = l+1;
}
return calNum;
}
int addition(int n1,int n2){return (n1+n2);}
int subtraction(int n1, int n2){return (n2-n1);}
int multiplication(int n1,int n2){return (n1*n2);}
int division(int n1, int n2){return int(n2/n1);}
I am using two stacks to print the output. I know my stacks are working perfectly fine but my output is not as I am expecting. Can someone help me?
infix expression is : (7+(((5*4)-(9-3))*1))
Answer should be : 21