I'm trying to code the RPN algorithm in C++, using a string as parameter.
I'm using a stack and a string to be read.
I know how the algorithm works, but I don't get a correct result, I always get 0. This is my code:
#include <iostream>
#include <stack>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
float RPN(string s) {
stack<int> p;
int n1, n2;
string values[s.size()];
for (unsigned int i = 0; i < s.size(); i++)
values[i] = s.at(i);
for (unsigned int i = 0; i < s.size(); i++) {
if (s.at(i) != '+' || s.at(i) != '-' || s.at(i) != '*'
|| s.at(i) != '/') {
int n;
istringstream(values[i]) >> n;
p.push(n);
}
else {
n1 = p.top();
p.pop();
n2 = p.top();
p.pop();
switch (s.at(i)) {
case '+':
p.push(n1 + n2);
break;
case '-':
p.push(n2 - n1);
break;
case '*':
p.push(n1 * n2);
break;
case '/':
p.push(n2 / n1);
break;
}
}
}
if (p.size()) {
int resul = p.top();
while (p.size())
p.pop();
return resul;
}
return 0;
}
This is the calling method:
void callRPN() {
string s1 = "56-";
string s2 = "65-";
string s3 = "843+2*-";
string s4 = "62+83-*4/";
cout << s1 << " valor: " << RPN(s1) << endl;
cout << s2 << " valor: " << RPN(s2) << endl;
cout << s3 << " valor: " << RPN(s3) << endl;
cout << s4 << " valor: " << RPN(s4) << endl;
}
And the console result:
56- valor: 0
65- valor: 0
843+2*- valor: 0
62+83-*4/ valor: 0
What is the error in my code? If someone could help me I would appreciate it. Thank you.