I wrote this code but only works at first operation for example 1 2 + and it prints 3 as result but I need to give it an expression like this: 1 2 + 3 4 - * and it must have to return the value 3. Instead of that, my code prints 2115.
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main() {
float op1,op2,value;
string expression;
cin>>expression;
stack<float>p;
for (int i=0;i<expression.length();++i){
if (expression[i] != '+' && expression[i] != '-' && expression[i] != '*' && expression[i] != '/'){
if (expression[i] != ' '){
p.push(expression[i]);
}
else{
continue;
}
}
if (expression[i] == '+'){
op1=p.top()-'0';p.pop();
op2=p.top()-'0';p.pop();
value=op1+op2;
p.push(value);
}
if (expression[i] == '-'){
op1=p.top()-'0';
p.pop();
op2=p.top()-'0';
p.pop();
value=op1-op2;
p.push(value);
}
if (expression[i]=='*'){
op1=p.top()-'0';
p.pop();
op2=p.top()-'0';
p.pop();
value=op1*op2;
p.push(value);
}
if (expression[i]=='/'){
op1=p.top()-'0';p.pop();
op2=p.top()-'0';p.pop();
value=op1/op2;
p.push(value);
}
}
cout<<value<<endl;
}