Segmentation fault (conversion to post-fixed notation)

Asked

Viewed 28 times

-1

The idea of the code is to convert a numerical expression to post-fixed notation (reverse polish), but I cannot run because it gives the error: Segmentation fault (core dumped)

Example:

Entry: ((A+B)*(C-(F/D)))

Output: AB+CFD/-*

#include <iostream>
#include <string>
#include <queue>
#include <stack>

using namespace std; 

int main() {   //    ((A+B)*(C-(F/D)))
  string inf = "((A+B)*(C-(F/D)))";
  stack <char> pilha;
  queue <char> posf;

  for(int i = 0; i<inf.size(); i++){
    switch (inf[i]){
      
      case '(': //empilha
      pilha.push(inf[i]);
      break;

      case ')': //move da pilha pra posf até encontrar '('
      while(inf[i] != '('){
        posf.push(pilha.top());
        pilha.pop();
      }
      pilha.pop();
      break;

      case '+':
      while(pilha.empty() || inf[i] != '('){
        posf.push(pilha.top());
        pilha.pop();
      }
      break;

      case '-':
      while(pilha.empty() || inf[i] != '('){
        posf.push(pilha.top());
        pilha.pop();
      }
      break;
      // joga na posfix o conteudo da pilha ate esta ficar vazia ou encontrar o inicio do bloco '('
        
      case '*':
      while(pilha.empty() || inf[i] != '(' || inf[i] != '+' || inf[i] != '-'){
        posf.push(pilha.top());
        pilha.pop();
      }
      break;

      case '/':
      while(pilha.empty() || inf[i] != '(' || inf[i] != '+' || inf[i] != '-'){
        posf.push(pilha.top());
        pilha.pop();
      }
      break;
      // joga na posfix o conteudo da pilha ate esta ficar vazia, encontrar o inicio do bloco '(' ou encontrar um operador de menor precedência '+' ou '-'

      default:
      if(inf[i] != ' '){
        posf.push(inf[i]); // copia operandos pra posf
      }
    }

    while(!posf.empty()){  // imprimir resultado no terminal
      cout << posf.front() << "";
      posf.pop();
    }
  }
}
  • 1

    You will have to review your entire algorithm. See this example here case ')':to enter that condition inf[i] has to be ). In that condition you enter a loop while(inf[i] != '(') the exit condition of which will never be reached, in which case inf[i] will always be ), then the code inside loop keeps repeating itself indefinitely until empty pilha and cause the error. The other conditions also have similar errors.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.