Функция не выводится в основную - PullRequest
0 голосов
/ 25 сентября 2018

Это для школы

Мне было поручено преобразовать выражение из инфикса в постфикс и оценить выражение.Я знаю, что это не самый эффективный способ решения этой проблемы, но у меня есть две отдельные функции (одна для преобразования нотации и другая для решения выражения).Моя функция преобразования работает, поэтому я полагаю, что нет никакой причины публиковать это, но моя функция решения ничего не выводит в мою основную.Ниже я опубликую необходимые функции, но дайте мне знать, если я просто опубликую всю свою программу.


#include <stdlib.h>
#include <iostream>
#include <stack>

using namespace std;

/*
Function precedence: This function will check which operator comes first. I
control which operator takes precedence by returning values.
*/
int precedence(char checkOperator){

  if(checkOperator == '^')
    return 4;
  else if(checkOperator == '*' || checkOperator == '/')
    return 3;
  else if(checkOperator == '+' || checkOperator == '-')
    return 2;
  else
    return 1;
}

/*
Function applyOperation: Just applies the operation
*/
int applyOperation(int valueOne, int valueTwo, char operation){

  switch(operation){
    case '+': return valueOne + valueTwo;
    case '-': return valueOne - valueTwo;
    case '*': return valueOne * valueTwo;
    case '/': return valueOne / valueTwo;
    }
}
/*
Function solveExpression: This function will solve the expression using a similar
approach used in function convertPostfix
*/
void solveExpression(string input){

  stack<int> operands;
  stack<char> operators;
  int stringLen = input.length();

  for(int i = 0; i < stringLen; i++){ //Traverse

    if(input[i] == ' '){ //Skip whitespace
      continue;
    }

    else if(input[i] == '('){ //Check if opening paren
            operators.push(input[i]);
    }

    else if(isdigit(input[i])){ //Check if theres a number then pushes it onto the operand stack
            int value = 0;
            value = value + (input[i]-'0'); //Not sure why -0 is needed, but I was getting crazy values without it
            operands.push(value);
        }

    //solve everything before the ')' is detected
    else if(input[i] == ')'){
            while(!operators.empty() && operators.top() != '('){
                int value2 = operands.top();
                operators.pop();

                int value1 = operands.top();
                operators.pop();

                char operatorBuffer = operators.top();
                operators.pop();

                operators.push(applyOperation(value1, value2, operatorBuffer));
            }
            operators.pop(); //pop '('
    }

    //Check and take care of operators
    else{
      while(!operators.empty() && precedence(operators.top()) >= precedence(input[i])){
        int value2 = operands.top();
                operands.pop();

                int value1 = operands.top();
                operands.pop();

                char operatorBuffer = operators.top();
                operators.pop();

                operands.push(applyOperation(value1, value2, operatorBuffer));
        }
        operators.push(input[i]); //push current into operator stack
    }
  }

  //Take care of everything that wasn't taken care of prior
  while(!operators.empty()){
    int value2 = operands.top();
    operands.pop();

    int value1 = operands.top();
    operands.pop();

    char operatorBuffer = operators.top();
    operators.pop();

    operands.push(applyOperation(value1, value2, operatorBuffer));
  }
  cout << operands.top();
   //The soultion of the expression should be stored at the top of the stack
}




int main(){

  string test = "(1 +2)*3";
    convertPostfix(test);
  solveExpression(test);
    return 0;

}

Проблема с моей программой (пока) заключается в том, что когдаЯ вызываю свою функцию решателя выражений, она ничего не выводит, но моя функция convertPostfix выводит ожидаемый результат.Любая помощь приветствуется!Итак, после некоторого дополнительного тестирования я выяснил, что что-то не так с чтением функции в скобках.

...