Infix to Posfix

Hello. Can someone help me with my code. Inserting the infix expression "2 + (3 + (4 + (5 + (6 + (7 + 8))))" it gives error in the initial part in which conversion is made to postfix. If I enter the expression "3 ^ 2 - 5 * 4 + 99", for example, it works perfectly. It seems to have some error in the code bound to the first expression. Grateful.

[code]
#include <iostream>
#include <sstream> //stringstream
#include <stack>
#include <string>
#include <list>
//#include <stdio.h>
#include <stdlib.h>
#include <math.h> //potencia

using namespace std;

int prioridade(char a) {
int p;
if (a == '^')
p = 1;
else if (a == '*' || a == '/')
p = 2;
else if (a == '+' || a == '-')
p = 3;
return p;
}
int main() {
string infix;
getline(cin, infix);
stack<char> operador_stack;
stringstream saida; //stringstream permite insercao e retirada de elementos

int cont_infix = infix.size();
int abre = 0; //contador para parenteses
int fecha = 0; //contador para parenteses
for(int i=0;i<cont_infix;i++){
if (infix[i]=='/' && infix[i+2] == '0'){
cout << "Error: Divide by zero" << endl;
exit(0);
}
if(infix[i]=='(')
abre++;
if (infix[i]==')')
fecha++;
if(infix[i]=='('&& infix[i+1]==')'){
cout << "Error: Invalid parentheses"<< endl;
exit(0);
}
}
if(fecha!=abre){
cout << "Error: Invalid parentheses"<< endl;
exit(0);
}

for (int i = 0; i < infix.length(); i++) {
if (infix[i] == '+' || infix[i] == '-' || infix[i] == '*' || infix[i] == '/' || infix[i] == '^') {
while (!operador_stack.empty() && prioridade(operador_stack.top()) <= prioridade(infix[i])) {
saida << operador_stack.top();
operador_stack.pop();
}
operador_stack.push(infix[i]);
} else if (infix[i] == '(') {
operador_stack.push(infix[i]);
} else if (infix[i] == ')') {
while (operador_stack.top() != '(') {
saida << operador_stack.top();
operador_stack.pop();
}
operador_stack.pop();
} else {
saida << infix[i];
}
}

while (!operador_stack.empty()) {
saida << operador_stack.top();
operador_stack.pop();
}
Topic archived. No new replies allowed.