-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();
}
}
}
You will have to review your entire algorithm. See this example here
case ')':
to enter that conditioninf[i]
has to be)
. In that condition you enter a loopwhile(inf[i] != '(')
the exit condition of which will never be reached, in which caseinf[i]
will always be)
, then the code inside loop keeps repeating itself indefinitely until emptypilha
and cause the error. The other conditions also have similar errors.– Augusto Vasques