Logo 
Search:

C++ Programming Articles

Submit Article
Home » Articles » C++ Programming » ParsingRSS Feeds

To parse a string using Recursive-Descent parser

Posted By: Reinhart Fischer     Category: C++ Programming     Views: 4008

To parse a string using Recursive-Descent parser.

Code for To parse a string using Recursive-Descent parser in C++ Programming

# include <iostream.h>
# include <ctype.h>
# include <conio.h>

struct tree
{
    char val;
    tree *Ltr;
    tree *Rtr;
};
tree *head;
int error=0;
char equ[15];
staticint i = 0;

void main()
{
clrscr();
    void read(tree*);
    tree * pro_E();
    tree * final;
    cout << "\n Enter The Equation: ";
    cin >> equ;
    final = pro_E();
    if(error == 0)
    {    cout <<"\n Result : ";
        read(final);
    }
getch();
}

tree * pro_E()
{
char chr;
    tree *L ,*R;
    tree * pro_T();
    tree * Enode;
    L = pro_T();
    while(equ[i] == '+' || equ[i] == '-')
    {    chr = equ[i];
        i++;
        R = pro_T();
        Enode = new tree;
        Enode->val = chr;
        Enode->Ltr = L;
        Enode->Rtr = R;
        L = Enode;
    }
return(L);
}
tree * pro_T()
{
char ch;
    tree *L, *R;
    tree *Tnode;
    tree * pro_V();
    L = pro_V();
    while (equ[i] == '*' || equ[i] == '/')
    {
        ch = equ[i];
        i++;
        R = pro_V();
        Tnode = new tree;
        Tnode->val = ch;
        Tnode->Ltr = L;
        Tnode->Rtr = R;
        L = Tnode;
    }
return(L);
}

tree * pro_V()
{
    tree * Inode;
    if (isalpha(equ[i]))
    {    Inode = new tree;
        Inode->val = equ[i];
        Inode->Ltr = Inode->Rtr =  NULL;
    }
    else
    {    cout << "Error In Expression";
        error = 1;
    }
    i++;
return(Inode);
}

void read(tree *nod)
{
    cout << nod->val;
    if(nod->Ltr != NULL)
        read(nod->Ltr);
    if(nod->Rtr != NULL)
        read(nod->Rtr);
}

/**************************************************
Output:
***************************************************

Enter The Equation: a+b*c/d
Result : +a/*bcd

**************************************************/
  
Share: 


Didn't find what you were looking for? Find more on To parse a string using Recursive-Descent parser Or get search suggestion and latest updates.

Reinhart Fischer
Reinhart Fischer author of To parse a string using Recursive-Descent parser is from Frankfurt, Germany.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!