Start New Discussion within our Software Development Community

We have an assignment to convert infix to postfix. And I have made this initial code. When this program is executed, I'd type any word that is not an operator or '(' or ')'. For example my input is "asd"
my output should be "asd" also. But in this code the ouput is only 'd'. Kindly how to fix this problem? tnx!

#include<iostream>
#include<cstdlib>
using namespace std;

const int size=50;
char infix[size], postfix[size], stack[size];

bool isOperator(char);
void push(char);
char pop();
void convertToPostfix(char infix);
int precedence(char operator1, char operator2);
char stackTop();
bool isEmpty();
void printStack();


int main()
{
    int j=0;
    char a, b, c;
    
    cout<<"Enter infix notation: ";
    gets(infix);
    
     for(int i=0; infix[i] != '\0' ; i++)
     {
             int j=0;
             char a, b, c;
             a=infix[i];
             
             if((!isOperator(a))&& (a != '(') &&(a != ')' ))
             {
                                   postfix[j++]= infix[i];
             
             }
     }
     
    
    cout<<"Equivalent postfix notation: "<<postfix<<endl;
    
    system("PAUSE");
    return 0;
    
}



bool isOperator(char symbol)
{
     if((symbol=='+') ||(symbol=='-') || (symbol=='*') || (symbol=='/') ||(symbol=='%') ||(symbol=='^'))
     return true;
     else 
     return false;
}

Watch your variable declarations. First you declare a, b, c and j. Then, within the for loop you declare them again. Now, every time the loop loops, your variables are re-declared. This means that j will be set to 0 every time you look at a new character.

Cheers
Emil Olofsson

This article has been dead for over six months. Start a new discussion instead.