Runtime error in my code...


 
Thread Tools Search this Thread
Top Forums Programming Runtime error in my code...
# 1  
Old 04-14-2011
Runtime error in my code...

INFIX TO POSTFIX CONVERSION :

Code:
//Convert an infix expression to postfix expression...

#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
char ifx[50],pfx[50],stk[50];
int top=-1,n;
void push(char ch)
{
    if(top!=n-1)
    {
        top++;
        stk[top]=ch;
    }
    else
        cout<<"\nThe stack is full.";    
}
char pop()
{
    char rmv;
    if(top!=-1)
    {
        rmv=stk[top];
        top--;
        return rmv;
    }
    else
        return '#';
}
char topele()
{
    char ch;
    if(top==-1)
    {
        ch='#';
        return ch;
    }   
    else
        ch=stk[top];
}
int chkpres(char ch)
{
    ch=topele();
    switch(ch)
    {
        case '^':return 7;
            break;
        case '/':return 6;
            break;
        case '*':return 5;
            break;
        case '+':return 4;
            break;
        case '-':return 3;
            break;
        default:return 0;
            break; 
     } 
}                 
/*int braces(char *s)
{
    int lftbr,rgtbr=0;
    for(int i=0;s[i];++i)
    {
        if(s[i]=='(')
            lftbr++;
        else
            rgtbr++;
    }
    if(lftbr==rgtbr)
        return 0;
    else if(lftbr<rgtbr)
        return 1;
    else return -1;
}*/
int main()
{
    char ele,elem,chk,popp,topp;
    int pre,pres;
    cout<<"\nEnter how many elements you want to enter in the infix expression: ";
    cin>>n;
    cout<<"\nEnter the infix expression: ";
    for(int i=0;i<n;++i)
        cin>>ifx[i]; 
    topp=topele();
    strcpy(pfx," ");
    for(int i=0,j=0;ifx[i]!='\0',pfx[j]!='\0';++i,++j)
    {
        ele=ifx[i];
        if(ele!='^' && ele!='*' && ele!='/' && ele!='+' && ele!='-')
            pfx[j++]=ifx[i];
        else if(ele=='^'||ele=='*'||ele=='/'||ele=='+'||ele=='-')
        {
            if(topp=='^'||topp=='*'||topp=='/'||topp=='+'||topp=='-')
            {
                pre=chkpres(ele);
                pres=chkpres(topp);
                if(pre>pres)
                {
                    push(pre);
                    top++;
                }
                else if(pre<=pres)
                    pfx[j++]=pres;
            }    
            else
            {
                push(ele);
                topp=ele;
            }
        }
        else if(ele=='(')
        {
            i++;
        }
        else if(ele==')')
        {
            while(topp!='#')
            {
                popp=topp;
                pfx[i]=popp;
            }
        }
        cout<<"---------------"<<pfx[j++];
    }
    cout<<"\nThe postfix expression is: ";
    for(int i=0;pfx[i]!='\0';++i)
    {
        cout<<pfx[i];
    }
    cout<<endl;
return 0;
}

# 2  
Old 04-14-2011
Quote:
Originally Posted by poonam.gaigole
INFIX TO POSTFIX CONVERSION :
Is that the error, or do we need to dig out our Bjarne Stroustrup books?

Have you tried adding some debug?

Last edited by Scott; 04-14-2011 at 03:07 PM..
# 3  
Old 04-15-2011
Yes, I have debugged this whole code. But what do you mean why adding some debug?
Actually the runtime error here is that my postfix expression is showing only a single character.

For example:

Quote:
Enter the infix expression: a * ( b + c ) / d

The postfix expression is: a

Instead it should show something like this...

Enter the infix expression: a * ( b + c ) / d

The postfix expression is: abc+*d/
Would you please help me work it out?
# 4  
Old 04-15-2011
This loop:
Code:
for(int i=0,j=0;ifx[i]!='\0',pfx[j]!='\0';++i,++j)

I don't think it does what you think it does.

Particularly this expression: ifx[i]!='\0',pfx[j]!='\0' Listing more than one in a row with commas doesn't do a logical and. It evaulates both statements, but only gives you the result of the second one! I think you must have meant (ifx[i]!='\0')&&(pfx[j]!='\0')

But that corrected expression still doesn't do what you think it does, because you're still assuming char arrays are strings. They're not exactly equivalent -- all strings may be char arrays, but that doesn't make all char arrays strings! NULLs don't just appear, something has to put them there.

Code:
// C adds a NULL at the end of "" strings for you
char *str="abcd";

// The C str* functions write NULLs, but also *need* nulls to work in the
// first place!  "asdf" has a NULL, so it works, and puts asdf\0 in buf[].
char buf[256]; strcpy(buf, "asdf");

// BUT an array is still JUST AN ARRAY.  It does not magically set other
// elements for you.  Setting b[0]='a', b[1]='b' does NOT set b[2]='\0'.
// It MIGHT have started that way, if you're lucky.  Or it might be garbage,
// or still hold a value you put in it last time, leaving your own code
// blissfully unaware that you intended the string to STOP at position 2.
char b[256]; b[0]='a'; b[1]='b';

// THIS is what a string is.
char c[256]; c[0]='a'; c[1]='b', c[2]='\0';

With that in mind, let's look at your loop again:

Code:
for(int i=0,j=0;(ifx[i]!='\0')&&(pfx[j]!='\0');++i,++j)

At program start, the contents of your pfx[] array are {' ', '\0', ???????? } because you called strcopy on it. The ???????? elements could be anything since nothing's been assigned to them yet.

First loop, i=0,j=0. It finds 'a' in ifx, so sets pfx[0]=ifx[0] (which happens to be 'a'), then adds 1 to j (because of pfx[j++]=...), then goes back up the for-loop, which adds to j again because of ++j.

Second loop, i=1, j=2. It checks if pfx[2], aka ?, is NULL. By sheer coincidence, it is, so the for-loop's condition becomes false, breaking the loop.

Some thoughts.
1) Why are you checking the value of pfx in the for-loop? You're writing to pfx, you don't need to care what used to be in it.

2) Why are you adding ++j every single loop? Not every loop will add a char. You could end up setting pfx[0], then pfx[3], then pfx[5], which will either create a string full of garbage or a string that ends too soon (depending on the previous contents of pfx). Only increment j when you actually add anything to pfx. You're also adding extra to i in places.

3) Why are you checking for NULLs when you have no strings? Either just use the length you got from before, or make it a string. When you want a string, the cheap+easy way is to use string functions:

Code:
#include <stdio.h> // for fgets
#include <ctype.h> // for isspace
#include <string.h> // for strchr, etc.

...

int i,j;
char pfx[50];
char ifx[50];

// Set everything in PFX to NULL.  As long as we set pfx[n] in order 0,1,2,...
// and don't go past pfx[48] it will always be a string now.
memset(pfx, 0, sizeof(pfx));
 
// Reads an entire raw line into buf, and adds the NULL terminator.
// You don't need to be told how long your expression is any more.
fgets(ifx, 50, stdin);

for(i=0,j=0; ifx[i] != '\0'; ++i)
{
        cout << "Beginning of loop, i="<<i<<" j=" <<j<<"\n";

        if(isspace(ifx[i]))
        {
                cout << "Ignoring space/line\n";
                continue;  // Ignore spaces and newlines
        }


        // Check ONCE and save the result so we don't need the same huge
        // if-statement three times.
        pre=chkpres(buf[i]);

        if(ifx[i] == '(') // Check this first to make it simpler
        {
                cout << "got (\n";
                // I don't understand why you had i++ here.  i already gets
                // incremented every loop by for().  I suspect you're supposed to
                // do something to the stack instead.
        }
        else if(ifx[i] == ')')
        {
                cout "got )\n";
                ...
        }
        else if(pre == 0) // Not a mathematical operator
        {
                cout << "got variable: "<<ifx[i]<<"\n";
                pfx[j++]=ifx[i];
        }
        else // Guaranteed to be a mathematical operator
        {
                cout << "got operator: "<<ifx[i] << " ";

                if(chkpres(topp) != 0)
                {
                     cout << "and top is also operator: "<<topp<<"\n";
                     // If topp is an operator
                }
                else
                {
                    cout << "but topp isn't an operator: "<<topp<<"\n";
                     // topp isn't an operator
                }
        }
}
// since pfx is guaranteed to be a string, we can print it in one whack
cout << "Loop done.  pfx is: " << pfx << "\n";


Last edited by Corona688; 04-15-2011 at 01:41 PM..
Login or Register to Ask a Question

Previous Thread | Next Thread

9 More Discussions You Might Find Interesting

1. Red Hat

Runtime Error Enable user directory apache

Hi I am exactly according to this link CentOS 6 - Apache httpd - Enable Userdir : Server World I Enabled userDirectory Server version: Apache/2.2.15 CentOS release 6.8 (Final) But Iget this Error Forbidden You don't have permission to access /~mn/index.html on this server Goal... (2 Replies)
Discussion started by: mnnn
2 Replies

2. Programming

Fortran runtime error: Insufficient data descriptors in format after reversion

Hello, I have some Fortran code that is providing the following error: At line 1165 of lapc_shells_2.f Fortran runtime error: Insufficient data descriptors in format after reversion Here are the lines just above and including 1165: WRITE (*,"('ATTEMPTING TO READ PLATE... (1 Reply)
Discussion started by: jm4smtddd
1 Replies

3. UNIX for Dummies Questions & Answers

No Java runtime environment (JRE) error

Hi all, I am trying to install a .bin file for that it requires IBMJava2-AMD64-142-JRE-1.4.2-13.8.x86_64.rpm to be installed. I have installed this rpm but when i try to install .bin file, it complains that no JRE found. How to solve this. Thanks in advance! #... (0 Replies)
Discussion started by: lramsb4u
0 Replies

4. Programming

Help... runtime error in my maxheap sort program

#include<iostream> using namespace std; int *a,size,heapsize; void maxheap(int *a,int j) { int l,r,largest,temp; l=2*j; r=(2*j)+1; for(j=0;j<size;++j) { if(l<=heapsize && a>a) largest=l; else largest=j; if(r<=heapsize... (5 Replies)
Discussion started by: poonam.gaigole
5 Replies

5. Shell Programming and Scripting

error code 137 and error code 35072

Hi while trying to run few scripts /afs/ae.ge.com/informatica/ardw/dev/bin/cdw_ar_update_recvbal.sh this script contains the below data load_dir=/afs/ae.ge.com/informatica/ardw/dev/data prog_dir=/afs/ae.ge.com/informatica/ardw/dev/bin ctl_dir=/afs/ae.ge.com/informatica/ardw/dev/ctl... (1 Reply)
Discussion started by: laxmi131
1 Replies

6. Programming

Runtime error in C++ Program - Help

All, I am getting this when i try to ran a program in HP unix. Things i came across 1. i have a system HP-UNIX where this same exe is working. 2. We have set a new HP_UNIX with the same configration and copied the exe to the new system we are getting this error. 3. Only... (3 Replies)
Discussion started by: arunkumar_mca
3 Replies

7. Solaris

Re:How to get the path during runtime?

Thank u vgesh99 It works well.. (1 Reply)
Discussion started by: Nandagopal
1 Replies

8. UNIX for Dummies Questions & Answers

Runtime Error...

My system did stay appears the error Run Time Library Error. What itīs? When the error appear, iīve to reboot my system and lost all I did. Is there the UNIX System problem? Please. I need help!!! (4 Replies)
Discussion started by: marpin
4 Replies

9. Solaris

Runtime error...

My interprise use a UNIX mainform for a instrumentation process control. The control use the FOXBORO INVENSYS system and they donīt gonna solve the problem the run time error. The run time error happen without logic explication. When everything itīs run perfectely and happenly appears the run time... (1 Reply)
Discussion started by: marpin
1 Replies
Login or Register to Ask a Question