#include <iostream>
#include <string>
#include <stack>
using namespace std;
float postix_evalute(string expr)
{
stack<float> stk;
for (int x = 0; x < expr.length(); x )
{
if (isdigit(expr[x]))
{
stk.push((expr[x] - '0'));
}
else
{
float val;
float op2 = stk.top();
stk.pop();
float op1 = stk.top();
stk.top();
switch (expr[x])
{
case ' ':
val = op1 op2;
break;
case '-':
val = op1 - op2;
break;
case '*':
val = op1 * op2;
break;
case '/':
val = op1 / op2;
break;
}
stk.push(val);
}
}
return stk.top();
}
int main()
{
string line;
cout << "The Value Of experssion" << endl;
cin >> line;
cout << postix_evalute(line) << endl;
return 0;
}
When I Enter This Expression for example: input=213 output=4 but i expect to get 24 which equal (21 3) so what should i do to make operation with more than on digit which equal in infix -> 21 3 anyone have anyidea how to do that
CodePudding user response:
You need a way to differentiate the tokens of your postfix expressions. For example, if the input is 213
, a parser would typically read that as 213
and
. For these simple expressions, you could separate the different tokens with whitespaces, as in 21 3
. Then, having that input in a string, you could read each token with an input string stream.
float postix_evalute(std::string input)
{
std::stack<float> stk;
std::istringstream iss{input};
std::string token{};
while (not iss.eof())
{
iss >> token;
try
{
stk.push(std::stof(token));
}
catch (const std::invalid_argument& ex)
{
assert(stk.size() >= 2);
float op2 = stk.top(); stk.pop();
float op1 = stk.top(); stk.pop();
float val{};
if (token == " ") { val = op1 op2; }
else if (token == "-") { val = op1 - op2; }
else if (token == "*") { val = op1 * op2; }
else if (token == "/") { val = op1 / op2; }
else { throw std::runtime_error{std::string{"unknown token: " token}}; }
stk.push(val);
}
}
return stk.top();
}
Demo 1: using 21 3
as an input.
Demo 2: using 21 3 #
as an input.