Thread: NEED HELP QUICKLY PLEASE How to print top value of stack without popping (calculator

  1. #1
    Registered User
    Join Date
    Feb 2005
    Posts
    14

    NEED HELP QUICKLY PLEASE How to print top value of stack without popping (calculator

    The following code acts as a reverse polish notation calculator

    example: 5 5 +
    outputs 10

    I'm trying to figure out a method to print the top element of the stack without popping using the '/' command, but no luck. I also want to add a command 'a' to duplicate the top value of the stack, and then a command 'c' to clear the stack. Any help would be appreciated thanks!

    Code:
    #include <stdio.h>
    #include <ctype.h>
    
    #define MAXOP 100         /* Max size of operand or operator */
    #define NUMBER '0'        /* Signal that a number was found */
    #define MAXVAL 100        /* Max value of stack */
    
    /* Functions Prototypes */
    
    double atof(char s[]);
    int getop(char []);
    void push(double);
    double pop(void);
    int getch(void);
    void ungetch(int);
    
    
    int main()
    
    {
            int c;
            int type = 0;
            int modulus;
            double op1 = 0.0;
            double op2 = 0.0;
            char s[MAXOP];
            int count = 0;
    
            while((type = getop(s)) != EOF){
    
      switch (type){
    
              case NUMBER:
                    push(atof(s));
                    break;
    
              /* Modulus operator code...returns the remainder
                 following the division between two integers
                 on the stack */
              case '%':
                    modulus = pop();
                    /* cast both values on the stack to ints */
                    if (modulus != 0) {
                      push((int)pop() % (int)modulus);
                    }
                    else {
                      printf("error: Cannot mod by 0\n");
                    }
                    break;
    
              case 'P':
                    ungetch(c);
                    printf("%d\n",c);
    
              case '+':
                    push(pop() + pop());
                    break;
    
             case '-':
                          op2 = pop();
                          push(pop() - op2);
    
                    break;
              case '/':
                      op2 = pop();
                    if (op2 != 0.0){
                      push(pop() / op2);
                    }
                    else{
                      printf("error: Zero Divisor\n");
                    }//end if()
                    break;
              case '\n':
                    printf("\t%.8g\n", pop());
                    break;
              default:
                    printf("error: unknown command %s\n", s);
                    break;
            }//end switch()
      }//end while()
    
    return 0;
    }//end main()
    
    
    
    
    /* ****************** Functions *********************** */
    
    
    double atof(char s[]) {    /* converts string s to type double */
    
        double val, power;
        int i, sign;
    
    
        for (i = 0; isspace(s[i]); i++) /* crunches out whitespace */
            ;
    
        sign = (s[i] == '-') ? -1 : 1;
           /* checks for minus sign, options
                                              for first character */
        if (s[i] == '+' || s[i] == '-')   /* checks if there is a sign at
                                          all, if so bumps over it */
            i++;
        for (val = 0.0; isdigit(s[i]); i++)
            val = 10.0 * val + (s[i] - '0');  /* subtracts out the 30 to
                                                account for ascii */
     if (s[i] == '.')
            i++;
        for (power = 1.0; isdigit(s[i]); i++) {
            val = 10.0 * val + (s[i] - '0');
            power *= 10.0;
        }
        return (sign * val / power);   /* returns expression */
    } /* end of atof */
    
    
    
    
    
    int sp = 0;
    
    double val[MAXVAL];
    
    
    void push(double f)
    {
    
            if(sp < MAXVAL){
              val[sp++] = f;
            }
            else{
              printf("error: stack full can't push %g\n",f);
            }//end if()
    }//End push()
    
    
    double pop(void)
    {
    
            if(sp > 0 ){
              return val[--sp];
            }
    
            else{
              return 0.0;
            }//end if()
    
    }//end pop()
    
    
    /* getop: get next operator or number operand */
    
    int getop(char s[])
    {
            int i = 0;
            int c = 0;
    
    
            while((s[0] = c = getch()) == ' ' || c == '\t');
    
            s[1] = '\0';
    
            if(!isdigit(c) && c == '?'){
                    printf("%d", c) ;
            }
       if(!isdigit(c) && c != '.'){
                    return c ;                /* not a number */
            }//End if()
    
            i = 0;
    
            if(isdigit(c)){
                    while(isdigit(s[++i] = c = getch()));
            }//End if()
    
    
            if(c == '.')        /* collect fraction part */
            {
                    while(isdigit(s[++i] = c = getch()));
            }//End if()
    
            s[i] = '\0';
    
            if(c != EOF){
              ungetch(c);
            }//end if()
    
            return NUMBER;
    
    }//End getop()
    
    /* Globals for get functions below */
    
    #define BUFSIZE 100
    
    char buf[BUFSIZE];
    
    int bufp = 0;
    
    
    int getch(void)
    {
            return(bufp > 0) ? buf[--bufp] : getchar();
    
    }// end getch()
    
    
    void ungetch(int c)
    
    {
            if(bufp >= BUFSIZE)
            {
              printf("ungetch: too many characters \n");
            }
            else
            {
              buf[bufp++] = c;
            }//End if
    }// End ungetch

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    1. There is already an atof function declared in the <math.h> or <stdlib.h> headers.
    2. Stack containers typically implement a top function that returns the value of the top element and does not pop (the C++ STL stack container does this). Perhaps you should code a top function of your own.
    3. Your pop and push functions operate on doubles. Unless it is really your intention to deliberately use the integer modulus operator then you should at least consider using the fmod function declared in <math.h>.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    Quote Originally Posted by ninjacookies
    I'm trying to figure out a method to print the top element of the stack without popping using the '/' command, but no luck.
    Write up a peek function that simply returns the top value. Or you can save the pop() value and push it again.
    Quote Originally Posted by ninjacookies
    I also want to add a command 'a' to duplicate the top value of the stack
    Okay. Either peek and push, or pop, push, and push.
    Quote Originally Posted by ninjacookies
    and then a command 'c' to clear the stack.
    All you have to do is set the stack pointer to the beginning. You don't even have to zero anything out.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > NEED HELP QUICKLY PLEASE
    Read my sig - I'll ignore your need for special attention from now on.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. What am I doing wrong, stack?
    By TeenyTig in forum C Programming
    Replies: 2
    Last Post: 05-27-2002, 02:12 PM
  2. Stack functions as arrays instead of node pointers
    By sballew in forum C Programming
    Replies: 8
    Last Post: 12-04-2001, 11:13 AM
  3. inputting line of text vs. integers in STACK
    By sballew in forum C Programming
    Replies: 17
    Last Post: 11-27-2001, 11:23 PM
  4. stack make file problem
    By puckett_m in forum C Programming
    Replies: 2
    Last Post: 11-22-2001, 11:51 AM
  5. c++ Reverse Polish Calculator Help
    By knight101 in forum C++ Programming
    Replies: 5
    Last Post: 11-12-2001, 09:31 AM