convert infix to postfix

Discussion in 'C Programming' started by caramel, Nov 18, 2005.

  1. caramel

    caramel Guest

    i've been working on this program forever! now i'm stuck and going
    insane because i keep getting a syntax error msg and i just can't see
    what the compiler is signaling to!

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    
    /* constants */
    #define TRUE 1
    #define FALSE 0
    
    /* structure for stack */
    typedef struct
    {
         char data[40];  /* array to hold stack contents */
         int tos;        /* top of the stack pointer */
    }
    STACK;
    
    /* function prototypes */
    void initStack(STACK *stack);
    void get_infix(char infix[]);
    void convertToPostfix(char infix[], char postfix[]);
    int isOperator(char c);
    int precedence(char operator1, char operator2);
    int pred_level(char ch);
    void push(STACK *stack, char value);
    char pop(STACK *stack);
    char stackTop(STACK *stack);
    int isEmpty(STACK *stack);
    int isFull(STACK *stack);
    void printResult(char infix[], char postfix[]);
    void print_msg(void);
    
    /* program entry point */
    int main()
    {
         char infix[40], postfix[40]="";
    
         /* convert from infix to postfix main function */
         convertToPostfix(infix, postfix);
         /* display the postfix equivalent */
         infix[strlen(infix)-2] = '\0';
         printResult(infix, postfix);
    
         return EXIT_SUCCESS;
    }
    
    /* initalise the stack */
    void initStack(STACK *stack)
    {
         stack->tos = -1;  /* stack is initially empty */
    }
    
    /* get infix expression from user */
    void get_infix(char infix[])
    {
         int i;
    
         printf("Enter infix expression: ");
         fflush(stdin);
    
         for ( i=0; i<40; )
         {
              if ( (infix[i] = getchar()) == '\n' )
              {
                   i++;
                   break;
              }
              else if ( !(isspace(infix[i])) )
                   i++;
         }
    
         infix[i] = '\0';
    }
    
    /* convert the infix expression to postfix notation */
    void convertToPostfix(char infix[], char postfix[])
    {
         int i, length;
         int j=0;
         char tos_ch;
         STACK stack;
    
         initStack(&stack); /* initialise stack */
         get_infix(infix);  /* get infix expression from user */
         length = strlen(infix);
    
         if ( length )
         {
              push(&stack, '(');
              strcat(infix, ")");
              length++;
    
              for ( i=0; i<length; i++ )
              {
                   /* if current operator in infix is digit */
                   if ( isdigit(infix[i]) )
                   {
                        postfix[j++] = infix[i];
                   }
                   /* if current operator in infix is left parenthesis */
                   else if ( infix[i] == '(' )
                   {
                        push(&stack, '(');
                   }
                   /* if current operator in infix is operator */
                   else if ( isOperator(infix[i]) )
                   {
                        while ( TRUE )
                        {
                             /* get tos */
                             tos_ch = stackTop(&stack);
    
                             /* no stack left */
                             if ( tos_ch == '\0' )
                             {
                                  printf("\nFull Stack!\n");
                                  print_msg();
                                  exit(1);
                             }
                             else
                             {
                                  if ( isOperator(tos_ch) )
                                  {
                                       if ( pred_level(tos_ch) >=
    pred_level(infix[i]) )
                                            postfix[j++] = pop(&stack);
                                       else
                                            break;
                                  }
                                  else
                                       break;
                             }
                        }
                        push(&stack, infix[i]);
                   }
                   /* if current operator in infix is right parenthesis */
                   else if ( infix[i] == ')' )
                   {
                        while ( TRUE )
                        {
                             /* get tos */
                             tos_ch = stackTop(&stack);
    
                             /* no stack left */
                             if ( tos_ch == '\0' )
                             {
                                  printf("\nFull Stack!\n");
                                  print_msg();
                                  exit(1);
                             }
                             else
                             {
                                  if ( tos_ch != '(' )
                                  {
                                       postfix[j++] = tos_ch;
                                       pop(&stack);
                                  }
                                  else
                                  {
                                       pop(&stack);
                                       break;
                                  }
                             }
                        }
                        continue;
                   }
              }
         }
    
         postfix[j] = '\0';
    }
    
    /* determine if c is an operator */
    switch (c) {
    	case '+':
    		return TRUE;
    		break;
    	case '-':
    		return TRUE;
    		break;
    	case '*':
    		return TRUE;
    		break;
    	case '/':
    		return TRUE;
    		break;
    	default:
    		return FALSE;
    		break;
         /*if ( c == '+' || c == '-' || c == '*' ||
               c == '/' || c == '%' || c == '^' )
         {
              return TRUE;
         }
         else
              return FALSE; */
    }
    
    /* determine precedence level */
    int pred_level(char ch)
    {
         if ( ch == '+' || ch == '-' )
              return 1;
         else
              return 2;
    }
    
    /* determine if the precedence of operator1 is less than,
       equal to, greater than the precedence of operator2 */
    int precedence(char operator1, char operator2)
    {
         if ( pred_level(operator1) > pred_level(operator2) )
              return 1;
         else if ( pred_level(operator1) < pred_level(operator2) )
              return -1;
         else
              return 0;
    }
    
    /* push a value on the stack */
    void push(STACK *stack, char value)
    {
         if ( !(isFull(stack)) )
         {
              (stack->tos)++;
              stack->data[stack->tos] = value;
         }
    }
    
    /* pop a value off the stack */
    char pop(STACK *stack)
    {
         char ch;
    
         if ( !(isEmpty(stack)) )
         {
              ch = stack->data[stack->tos];
              (stack->tos)--;
              return ch;
         }
         else
              return '\0';
    }
    
    /* return the top value of the stack without popping the stack */
    char stackTop(STACK *stack)
    {
         if ( !(isEmpty(stack)) )
              return stack->data[stack->tos];
         else
              return '\0';
    }
    
    /* determine if stack is empty */
    int isEmpty(STACK *stack)
    {
         /* empty */
         if ( stack->tos == -1 )
              return TRUE;
         /* not empty */
         else
              return FALSE;
    }
    
    /* determine if stack is full */
    int isFull(STACK *stack)
    {
         /* full */
         if ( stack->tos == 19 )
              return TRUE;
         /* not full */
         else
              return FALSE;
    }
    
    /* display the result postfix expression */
    void printResult(char infix[], char postfix[])
    {
         /*system("cls");*/
         printf("\n\n");
         printf("Infix notation: %d%s\n", infix);
         printf("Postfix notation: %d%s\n\n", postfix);
         print_msg();
    }
    
    /* print exit message */
    void print_msg(void)
    {
         printf("Hit <RETURN> to exit...");
         fflush(stdin);
         getchar();
    }
    
    the error msg i get is: syntax error before "switch"

    i don't get it :S ... any suggestions?
     
    caramel, Nov 18, 2005
    #1
    1. Advertising

  2. caramel

    caramel Guest

    ok i finally fixed the error!!! but the program outputs operators and
    numbers, no variables

    for example: if i input a*b+c*d/2 , it gives **2/+

    so what now?
     
    caramel, Nov 19, 2005
    #2
    1. Advertising

  3. caramel

    pete Guest

    caramel wrote:

    > the error msg i get is: syntax error before "switch"
    >
    > i don't get it :S ... any suggestions?


    Which function is the switch statement supposed to be in?

    --
    pete
     
    pete, Nov 19, 2005
    #3
  4. caramel

    bitshadow Guest

    pete wrote:
    > caramel wrote:
    >
    > > the error msg i get is: syntax error before "switch"
    > >
    > > i don't get it :S ... any suggestions?

    >
    > Which function is the switch statement supposed to be in?
    >
    > --

    the switch is in void convertToPostfix(char infix[], char postfix[])
    what i want to know is where is 'c'. i've attempted to trace the
    program state and can't find out where it is. You don't seem to pass it
    as an argument. Also flushing stdin causes undefined behaviour, take
    that out.
     
    bitshadow, Nov 19, 2005
    #4
  5. caramel

    pete Guest

    bitshadow wrote:
    >
    > pete wrote:
    > > caramel wrote:
    > >
    > > > the error msg i get is: syntax error before "switch"
    > > >
    > > > i don't get it :S ... any suggestions?

    > >
    > > Which function is the switch statement supposed to be in?
    > >
    > > --

    > the switch is in void convertToPostfix(char infix[], char postfix[])
    > what i want to know is where is 'c'.


    Maybe that's where it's supposed to be,
    which is what I asked, but that's not where it is.

    I'd like to see an example of the output is supposed to be
    for a given input.

    --
    pete
     
    pete, Nov 19, 2005
    #5
  6. caramel

    pete Guest

    pete wrote:
    >
    > bitshadow wrote:
    > >
    > > pete wrote:
    > > > caramel wrote:
    > > >
    > > > > the error msg i get is: syntax error before "switch"
    > > > >
    > > > > i don't get it :S ... any suggestions?
    > > >
    > > > Which function is the switch statement supposed to be in?
    > > >
    > > > --

    > > the switch is in void convertToPostfix(char infix[], char postfix[])
    > > what i want to know is where is 'c'.

    >
    > Maybe that's where it's supposed to be,
    > which is what I asked, but that's not where it is.


    I think the switch is supposed to be in isOperator().
    Where isOperator is, I don't know.

    --
    pete
     
    pete, Nov 19, 2005
    #6
  7. caramel

    caramel Guest

    well i fixed the switch, now i need to get it to print variables

    it works as intended with numbers and operators, but for some reason it
    does not print the variables entered to the console
     
    caramel, Nov 19, 2005
    #7
  8. caramel

    pete Guest

    caramel wrote:
    >
    > well i fixed the switch, now i need to get it to print variables
    >
    > it works as intended with numbers and operators,
    > but for some reason it
    > does not print the variables entered to the console


    Probably has something to do with the current state of your code.

    --
    pete
     
    pete, Nov 19, 2005
    #8
  9. caramel

    caramel Guest

    true, i was wondering if anyone can point out any mistake(s) or suggest
    a fragment of code i can insert to display variables
     
    caramel, Nov 19, 2005
    #9
  10. On 18 Nov 2005 15:42:10 -0800, "caramel" <> wrote:

    >i've been working on this program forever! now i'm stuck and going
    >insane because i keep getting a syntax error msg and i just can't see
    >what the compiler is signaling to!
    >

    snip
    >/* convert the infix expression to postfix notation */
    >void convertToPostfix(char infix[], char postfix[])


    You did an excellent job of lining up all your braces.

    >{

    snip
    > if ( length )
    > {

    snip
    > for ( i=0; i<length; i++ )
    > {

    snip
    > if ( isdigit(infix) )
    > {

    snip
    > }

    snip
    > else if ( infix == '(' )
    > {

    snip
    > }

    snip
    > else if ( isOperator(infix) )
    > {
    > while ( TRUE )
    > {

    snip
    > if ( tos_ch == '\0' )
    > {

    snip
    > }
    > else
    > {
    > if ( isOperator(tos_ch) )
    > {
    > if ( pred_level(tos_ch) >= pred_level(infix) )

    snip
    > else

    snip
    > }
    > else

    snip
    > }
    > }

    snip
    > }

    snip
    > else if ( infix == ')' )
    > {
    > while ( TRUE )
    > {

    snip
    > if ( tos_ch == '\0' )
    > {

    snip
    > }
    > else
    > {
    > if ( tos_ch != '(' )
    > {

    snip
    > }
    > else
    > {

    snip
    > }
    > }
    > }

    snip
    > }
    > }
    > }

    snip
    >}


    This brace ends the function.

    >
    >/* determine if c is an operator */
    >switch (c) {


    You cannot put a switch statement (or most other statements) outside
    of a function.

    snip


    <<Remove the del for email>>
     
    Barry Schwarz, Nov 19, 2005
    #10
  11. caramel

    caramel Guest

    the brace after (c) ?

    and thanks for the compliment, i am a neat freak ;)


    but u guys the program works fine now, and i get no more error msgs,
    just that one problem that it drops out the variables and only displays
    numbers and operators... how do i fix that?
     
    caramel, Nov 19, 2005
    #11
  12. caramel

    Guest

    caramel wrote:
    > the brace after (c) ?
    >
    > and thanks for the compliment, i am a neat freak ;)
    >
    >
    > but u guys the program works fine now, and i get no more error msgs,
    > just that one problem that it drops out the variables and only displays
    > numbers and operators... how do i fix that?


    In your for loop in convertToPostfix, you checked for:

    1. isdigit
    2. the opening bracket '('
    3. isOperator
    4. the closing bracket ')'

    but ignored everything else. That's why you keep droping variables. I
    suggest that after the last else if put an else to accept everything
    else as variables. If you want to restrict variables to alphabets then
    check for isAnAcceptableVariable.
     
    , Nov 19, 2005
    #12
  13. caramel

    caramel Guest

    thanks for the input, i'll go through with that and see what happens

    many thanks and much appreciation to all who shared their thoughts :)
     
    caramel, Nov 19, 2005
    #13
  14. "caramel" <> writes:
    > the brace after (c) ?
    >
    > and thanks for the compliment, i am a neat freak ;)
    >
    >
    > but u guys the program works fine now, and i get no more error msgs,
    > just that one problem that it drops out the variables and only displays
    > numbers and operators... how do i fix that?


    Some suggestions on posting style:

    Don't assume your readers can see the article to which you're
    replying. You need to provide some context. Google makes it
    unecessarily difficult to do this, but there is a workaround (which
    has been posted here over 1000 times):

    If you want to post a followup via groups.google.com, don't use
    the broken "Reply" link at the bottom of the article. Click on
    "show options" at the top of the article, then click on the
    "Reply" at the bottom of the article headers.

    Also, please don't use abbreviations like "u" for "you". They just
    make your text more difficult to read. Proper capitalization is also
    helpful.

    --
    Keith Thompson (The_Other_Keith) <http://www.ghoti.net/~kst>
    San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
    We must do something. This is something. Therefore, we must do this.
     
    Keith Thompson, Nov 19, 2005
    #14
  15. In article <>,
    Keith Thompson <> wrote:
    ....
    >Don't assume your readers can see the article to which you're
    >replying. You need to provide some context. Google makes it
    >unecessarily difficult to do this, but there is a workaround (which
    >has been posted here over 1000 times):
    >
    > If you want to post a followup via groups.google.com, don't use
    > the broken "Reply" link at the bottom of the article. Click on
    > "show options" at the top of the article, then click on the
    > "Reply" at the bottom of the article headers.


    You are wasting your breath. They'll never get it. And I'll tell you why.

    Imagine that there's a mouse - and the mouse is the Usenet. You and I can
    see that it is a mouse and we behave accordingly. But now there is a class
    of users (we'll call them "googlers") that are wearing these funny weird
    glasses that make them see not a mouse, but an elephant. Seeing an
    elephant (i.e., the Usenet as a web page), they also behave accordingly.
    And no amount of verbiage from us is going to convince them that it's not
    an elephant - that it is only a mouse.

    To make this more clear, to a googler, it doesn't make any sense to "quote"
    (whatever the heck that is...), in fact, to do so would be absurd, when all
    the rest of the articles in the thread are right there in front of their
    faces (just as clear as the trunk on that mouse, er, elephant). And no
    amount of verbiage from us is going to convince them not to believe what
    they see. The point is you can *never* convince someone that what they see
    isn't reality. The only way you can address the problem is to help them
    fix their eyesight (or help them remove their funny glasses).

    >Also, please don't use abbreviations like "u" for "you". They just
    >make your text more difficult to read. Proper capitalization is also
    >helpful.


    Good advice. tnk u.
     
    Kenny McCormack, Nov 19, 2005
    #15
  16. caramel

    caramel Guest

    Kenny McCormack wrote:
    > In article <>,
    > Keith Thompson <> wrote:
    > ...
    > >Don't assume your readers can see the article to which you're
    > >replying. You need to provide some context. Google makes it
    > >unecessarily difficult to do this, but there is a workaround (which
    > >has been posted here over 1000 times):
    > >
    > > If you want to post a followup via groups.google.com, don't use
    > > the broken "Reply" link at the bottom of the article. Click on
    > > "show options" at the top of the article, then click on the
    > > "Reply" at the bottom of the article headers.

    >
    > You are wasting your breath. They'll never get it. And I'll tell you why.
    >
    > Imagine that there's a mouse - and the mouse is the Usenet. You and I can
    > see that it is a mouse and we behave accordingly. But now there is a class
    > of users (we'll call them "googlers") that are wearing these funny weird
    > glasses that make them see not a mouse, but an elephant. Seeing an
    > elephant (i.e., the Usenet as a web page), they also behave accordingly.
    > And no amount of verbiage from us is going to convince them that it's not
    > an elephant - that it is only a mouse.
    >
    > To make this more clear, to a googler, it doesn't make any sense to "quote"
    > (whatever the heck that is...), in fact, to do so would be absurd, when all
    > the rest of the articles in the thread are right there in front of their
    > faces (just as clear as the trunk on that mouse, er, elephant). And no
    > amount of verbiage from us is going to convince them not to believe what
    > they see. The point is you can *never* convince someone that what they see
    > isn't reality. The only way you can address the problem is to help them
    > fix their eyesight (or help them remove their funny glasses).
    >
    > >Also, please don't use abbreviations like "u" for "you". They just
    > >make your text more difficult to read. Proper capitalization is also
    > >helpful.

    >
    > Good advice. tnk u.


    Hmmm, well yes, you're right. I thought this Google board thing works
    like normal forums do. Guess I was wrong! I still don't really
    understand why you can't refer to previous posts, but nonetheless I
    will do my best to adhere to your rules. Sorry for any inconvenience!
     
    caramel, Nov 19, 2005
    #16
  17. On 19 Nov 2005 08:02:01 -0800, in comp.lang.c , "caramel"
    <> wrote:

    >
    >Hmmm, well yes, you're right. I thought this Google board thing works
    >like normal forums do.


    Google doesn't work like anything. Its a web interface to usenet, and
    the majority of people reading usenet do not use google, but proper
    newsreaders which display the information in a very different format.

    >I still don't really
    >understand why you can't refer to previous posts,


    Because the servers other people are getting the posts from may not
    carry all the old messages, or the reader may not want to have to
    fetch additional material, or may be on dialup where every second
    downloading costs money.

    Another way to think about this: each message you send is a sort of
    email, sent to dozens, possibly thousands of people who are reading
    the newsgroup. You can't realistically expect them all to have kept
    all the email they recieved, just in case they needed to refer back to
    it.

    >but nonetheless I will do my best to adhere to your rules.


    Thanks
    --
    Mark McIntyre
    CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
    CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

    ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
    http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
    ----= East and West-Coast Server Farms - Total Privacy via Encryption =----
     
    Mark McIntyre, Nov 19, 2005
    #17
  18. "caramel" <> writes:
    [...]
    > Hmmm, well yes, you're right. I thought this Google board thing works
    > like normal forums do. Guess I was wrong! I still don't really
    > understand why you can't refer to previous posts, but nonetheless I
    > will do my best to adhere to your rules. Sorry for any inconvenience!


    Google Groups is an interface to Usenet, a system that has been in
    existence for decades longer than Google has. Unfortunately, the
    folks at Google screwed up the interface, making things difficult for
    those of us who use other interfaces. Our attempts to get them to fix
    there broken interface have so far been unsuccessful.

    (Incidentally, Kenny McCormack is a self-proclaimed troll. Please
    ignore him.)

    --
    Keith Thompson (The_Other_Keith) <http://www.ghoti.net/~kst>
    San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
    We must do something. This is something. Therefore, we must do this.
     
    Keith Thompson, Nov 19, 2005
    #18
  19. In article <>,
    Keith Thompson <> wrote:
    ....
    >(Incidentally, Kenny McCormack is a self-proclaimed troll. Please
    >ignore him.)


    But at least he knows how to spell 'their' - as in 'their interface'.
     
    Kenny McCormack, Nov 19, 2005
    #19
  20. caramel

    Barry Guest

    "Keith Thompson" <> wrote in message
    news:...
    > "caramel" <> writes:
    > [...]
    > > Hmmm, well yes, you're right. I thought this Google board thing works
    > > like normal forums do. Guess I was wrong! I still don't really
    > > understand why you can't refer to previous posts, but nonetheless I
    > > will do my best to adhere to your rules. Sorry for any inconvenience!

    >
    > Google Groups is an interface to Usenet, a system that has been in
    > existence for decades longer than Google has. Unfortunately, the
    > folks at Google screwed up the interface, making things difficult for
    > those of us who use other interfaces. Our attempts to get them to fix
    > there broken interface have so far been unsuccessful.
    >
    > (Incidentally, Kenny McCormack is a self-proclaimed troll. Please
    > ignore him.)
    >
    > --
    > Keith Thompson (The_Other_Keith)

    <http://www.ghoti.net/~kst>
    > San Diego Supercomputer Center <*>

    <http://users.sdsc.edu/~kst>
    > We must do something. This is something. Therefore, we must do this.


    And I thought I was the only one who thinks Kenny McCormack is an asswipe.
     
    Barry, Nov 19, 2005
    #20
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. KidLogik
    Replies:
    5
    Views:
    7,064
    David Rubin
    Feb 3, 2004
  2. Replies:
    1
    Views:
    458
    mlimber
    Dec 28, 2006
  3. Xah Lee
    Replies:
    30
    Views:
    1,813
    Peter J. Holzer
    Jun 16, 2007
  4. Xah Lee
    Replies:
    30
    Views:
    1,267
    Peter J. Holzer
    Jun 16, 2007
  5. Tameem
    Replies:
    454
    Views:
    12,227
Loading...

Share This Page