vendredi 23 février 2018

c++ Evaluating expression operator precedence not working

I'm making a program that evaluates arithmetic expressions through use of stacks. My code functions and does the proper calculation of an expression for the most part, however; when it comes to long expressions it doesn't follow the precedence I set out with the if statements.

void doOp() {

int x = stoi(valStk.top());
valStk.pop();
int y = stoi(valStk.top());
valStk.pop();
string op = opStk.top();
opStk.pop();

double result;
string result2;
if (op == "*")
{
    result = x * y;
    valStk.push(to_string(result));
}
else if (op == "/")
{
    result = x / y;
    valStk.push(to_string(result));
}
else if (op == "+")
{
    result = x + y;
    valStk.push(to_string(result));
}
else if (op == "-")
{
    result = y - x;
    valStk.push(to_string(result));
}
else if (op == "=>")
{
    if (x=y || x>y )
    {
        result2 = "true";
        valStk.push(result2);
    }
    else
    {
        result2 = "false";
        valStk.push(result2);
    }
}
else if (op == "<=")
{
    if (x = y || x<y)
    {
        result2 = "true";
        valStk.push(result2);
    }
    else
    {
        result2 = "false";
        valStk.push(result2);
    }
}
}

int main() {

string expression;
string quit;
int counter = 1;

while (quit != "1")
{
    std::cout << "Enter an expression item " << counter << ": ";
    std::cin >> expression;
    checkStr(expression);
    std::cout << "Are you done entering expression? Enter 1 to quit. ";
    std::cin >> quit;
    counter++;
}

for (int i = 0; i < valStk.size(); i++)
{
    doOp();
}

std::cout << valStk.top() << endl;
}

shouldn't the compiler use the order of the if statements to create precedence?

Aucun commentaire:

Enregistrer un commentaire