Can anyone help me on how to display my infix notation with parentheses?
4+3 should be displayed as (4+3)

also, my code only works for simple expressions like 4+0, it can translate the infix,prefix,and postfix correctly, but when the expression grows, for some reason, its outputting the incorrect notations for the prefix and postfix. maybe i havent done enough checking. im so lost.

please help me):

template <class Item>
    void infix(exp_tree_node<Item>* root_ptr){         
        if(root_ptr != NULL) {             
            infix(root_ptr->left());
	    if(root_ptr->getOp() == 'l'){
                cout << root_ptr->data();//print the data field 
            } else {
                cout << root_ptr->getOp(); // print the operator
            }
            infix(root_ptr->right());  
            }
        }
    }
    
    template <class Item>
    void prefix(exp_tree_node<Item>* root_ptr){
        if(root_ptr != NULL) {
            if(root_ptr->getOp() =='l') {
                cout << root_ptr->data();    
            }else {
                cout << root_ptr->getOp();
            }    
            prefix(root_ptr->left());
            prefix(root_ptr->right());
        }
    }        
        
    template <class Item>
    void postfix(exp_tree_node<Item>* root_ptr){
        if(root_ptr != NULL) {
            postfix(root_ptr->left());
            postfix(root_ptr->right());          
            if(root_ptr->getOp() == 'l') {
                cout << root_ptr->data();                   
            }else {
               cout << root_ptr->getOp(); 
            }
            
        }
    }

if the complete cpp template file is needed, i can upload it. thanks

>Can anyone help me on how to display my infix notation with parentheses?
It's simple enough, just print your parens at the operator level for sub-expressions you want to wrap (you probably want to exclude unary operators):

template <class Item>
void infix(exp_tree_node<Item>* root)
{
    if (root != NULL) {
        if (root->is_op() && !root->is_unary())
            cout.put('(');

        infix(root->left());
        cout<< root->value();
        infix(root->right());

        if (root->is_op() && !root->is_unary())
            cout.put(')');
    }
}

>when the expression grows, for some reason, its outputting the incorrect notations for the prefix and postfix
Can you provide an example?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.