RPN calculator

This is a discussion on RPN calculator within the C Programming forums, part of the General Programming Boards category; Alright so my professor gave us an assignment to make an RPN calculator. He supplied us with the code to ...

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    15

    RPN calculator

    Alright so my professor gave us an assignment to make an RPN calculator. He supplied us with the code to read in values and we have to write the code to put the values in an array and do the calculations. I understand the basics of arrays but I'm having a tough time trying to put the numbers that are inputted, into an array.

    Code:
    //Header Files
    #include <stdio.h>
    #include <math.h>
    
    #define MAX_BUFFER_SIZE 100
    #define MAX_STACK_SIZE 100
    
    
    //Start of main function
    int main(void)
    {
    	//Declarations
        char buff[MAX_BUFFER_SIZE];
        double i, x, stack[MAX_STACK_SIZE];
        int num_operand=0;
    
    	//Program Title
        printf("            REVERSE POLISH CALCULATOR\n");
        printf("-------------------------------------------------\n");
    
        //This reads a string from the user
    	if( scanf("%s", buff) < 1 )
        {
           printf("I did not understand\n");
           return 0;
        }
    
        //Checks to see if the user entered a number
        if(isdigit(buff[0]) || isdigit(buff[1]))
        {
           
    	//Turns string into number and puts value in x
    	sscanf( buff, "%lf", &x);
    	
    	//Place statements here to handle getting a number 
    	for(i = 0; i < MAX_STACK_SIZE; i++)
    	{
    		stack[num_operand]=x;
    		num_operand ++;
            }
    	   
        } else {
    	//Place statements to do operations
    
    
        }
    
    	//Exit program
    	printf("Press RETURN to exit program \n");
    	getchar(); getchar();
    	return 0;
     }
    What's in red is what I've put in so far and the rest is what he supplied. I need to put the values that are inputted into an array. Am I on the right track with the for loop?

    Also, I really don't understand how the values you want to put in are inputted.. When I run the program, I can type a number in, hit enter, and the program just stops..

  2. #2
    Registered User
    Join Date
    Feb 2009
    Posts
    16
    Your for loop

    Code:
    	for(i = 0; i < MAX_STACK_SIZE; i++)
    	{
    		stack[num_operand]=x;
    		num_operand ++;
            }
    is off. Essentially, its putting the first number element in the string into the stack 100 times over. So your stack is just 100 n (where n is the first number the user inputs). What its doing is completely irrelevant, though you are on the right track. Check this algorithm out. It should visually clarify what needs to be done.

    I'm not a %100 sure on this, but I think it's inappropriate to use sscanf. I believe sscanf should be used when you know the formating of the buffer, which is not the case here.

  3. #3
    Registered User
    Join Date
    Mar 2009
    Posts
    15
    That's what I figured.. I've read through that whole article. Haha my professor basically printed that off and gave it to us and said, "There's your next assignment".

    So I should use a for loop though? To put the values in the stack?

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I would use a while loop. How will you know in advance how many numbers or arithmetic operators, will be in your expression. It could be just 5 + 2, or it could be 5 + 2 + 4 * 15.

    There is no need to go through the entire stack (either one, since they are both first in last out stacks, I believe), to push a number onto the stack, or to pop a number (or operator), off of the stack. If you have 2 operators on the stack, you move two operators, not 100.

  5. #5
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by Raskalnikov View Post
    I'm not a %100 sure on this, but I think it's inappropriate to use sscanf. I believe sscanf should be used when you know the formating of the buffer, which is not the case here.
    It is acceptable to use sscanf in the way it is. It checks if one of the first two characters is a digit. This, I presume is to cover numbers starting with '.' or '-' (or '+').

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Looking at it again: I think the whole framework is somewhat broken. In rpn, you would have a format of "5 2 +". Since scanf("%s", buff) will stop at the first space, it will only read 5. There is, in the posted code, no way to read more info from the console, so how is it going to get to the 2 and +?

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  7. #7
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Your programs gets the string as input from the user.

    I'd go through the string char by char. If it's a number, then put it on the number stack. If it's an operator, push it onto the operator stack. You don't need or want scanf, sscanf, etc. Roll your own.

    To that end I'd use 3 functions, and call them only after your program has checked out the strings next char's to see what they are:

    "5 * 4.3 + 18"

    pushInt(5) // is between 0 and 9.
    pushDouble(4.3) //because you found the decimal point with the number
    pushOperator(+) //not between 0 and 9, must be an operator or a decimal point.

    Sure, they're incredibly small functions, but I'd want to keep the logic in them, away from the logic that traverses the string.

    Then have 3 functions just like it, but doing the pop's off the stack, instead of the push's, onto the stack.

  8. #8
    Registered User
    Join Date
    Mar 2009
    Posts
    15
    Ok I got some more help from the professor today and made some good progress. I think I can handle it from here but there is one problem.

    When I run my code, the only error I get is at the end and it says "syntax error at the end of input". It's literally on the very bottom below all my code. What would cause an error like that? I'm using XCode if that helps. I don't want someone to have to go through my entire code and debug it or something like that so I refrained from putting my code up. Is there something that would generally cause an error like that?

  9. #9
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Either (1) mismatched braces or (2) no blank line at the end of the program (a C program is technically supposed to end with a new-line character, not a close brace).

  10. #10
    Registered User
    Join Date
    Feb 2009
    Posts
    16
    Can you please post what you've corrected? I'm interested in how you've managed to parse the string - using sscanf or not.

  11. #11
    Registered User
    Join Date
    Mar 2009
    Posts
    15
    Sure. Here's where I'm at currently.

    Code:
    //Header Files
    #include <stdio.h>
    #include <math.h>
    #include <ctype.h>
    
    #define MAX_BUFFER_SIZE 100
    #define MAX_STACK_SIZE 100
    
    
    //Start of main function
    int main(void)
    {
    	//Declarations
        char buff[MAX_BUFFER_SIZE];
        double x, stack[MAX_STACK_SIZE];
    	int i, num_operand=0;
    
    	//Program Title
        printf("            REVERSE POLISH CALCULATOR\n");
        printf("-------------------------------------------------\n");
    
    	while(x != 'q')
    	{
    		//This reads a string from the user
    		if( scanf("%s", buff) < 1 )
    		{
    			printf("I did not understand \n");
    			return 0;
    		}
    
    		//Checks to see if the user entered a number
    		if(isdigit(buff[0]) || isdigit(buff[1]))
    		{
           
    		//Turns string into number and puts value in x
    		sscanf( buff, "%lf", &x);
    	
    			//Place statements here to handle getting a number 
    			if (num_operand < MAX_STACK_SIZE)
    			{
    				stack[num_operand]=x;
    				num_operand ++;
    			} 
    			else 
    			{
    				printf("No more space on stack \n");
    			}
    		
    		} 
    		else 
    		{
    		//Place statements to do operations
    			switch(buff[0])
    			{
    				//To handle addition
    				case '+':
    					if(num_operand >= 2)
    					{
    						stack[num_operand] = stack[num_operand - 1] + stack[num_operand - 2];
    						num_operand --;
    					} 
    					else 
    					{
    						printf("Not enough operands in stack for operation \n");
    					}
    					break;
    				//To handle subtraction
    				case '-':
    			
    					break;
    				//To handle multiplication
    				case '*':
    			
    					break;
    				//To handle division
    				case '/':
    			
    					break;
    				//To handle listing what's currently in the stack
    				case 'l':
    					printf("Values in the stack are: \n");
    					for(i = 0; i < num_operand; i++)
    					{
    						printf("--%5.3lf \n", stack[i]);
    					}
    					break;
    				//To handle popping a number off the stack
    				case 'p':
    					num_operand--;
    					break;
    				//To handle quitting the program
    				case 'q':
    					return 0;
    					break;
    			}
    		}
    	}
    }
    I think I've got the input part down, now I'm working on the mathematical side of things. I know my addition switch is wrong already cause I doesn't work when I run it . Maybe a clue on how to add numbers in array?
    Last edited by bassist11; 03-02-2009 at 08:19 PM.

  12. #12
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You *push* the numbers and the operators onto their respective stacks.

    To do the math, you need to *pop* them back off, in FILO order - like a stack of plates at a restaurant (one of those spring loaded kinds was always a good image for me).

    Code:
    (pseudo mostly)
    
    tempAnswer = 0;
    numbers[0] pops into num1
    numbers[1] pops into num2  //or numbers[0] again if you adjust the stack between pops
    //and if you didn't adjust the stack before this point, do it *now*.
    
    operators[0] pops off and into op1
    
    switch case (op1)  {
    
    etc.
    
    If you can imagine that stack of plates, and strictly follow that picture into your logic, without shortcuts, it will all fall into place, quicker.
    
    tempAnswer += num1 + num2;

  13. #13
    Registered User
    Join Date
    Feb 2009
    Posts
    16
    Does the user hit return when entering each new value? Or is the whole equation entered in as one string?

  14. #14
    Registered User
    Join Date
    Mar 2009
    Posts
    15
    Yes. You put a number in and hit enter and it puts it on the stack. That's where I was confused too but my instructor helped me out there.

  15. #15
    HelpingYouHelpUsHelpUsAll
    Join Date
    Dec 2007
    Location
    In your nightmares
    Posts
    223
    I did one of these using char *s, and when an operator came along - fill both operands then call a function to do the operation. Worked for me. I am not going to post it because that would be cheating (& it is a work in progress).
    long time no C; //seige
    You miss 100% of the people you don't C;
    Code:
    if (language != LANG_C && language != LANG_CPP)
        drown(language);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. GUI Calculator - Critique
    By The Brain in forum Windows Programming
    Replies: 1
    Last Post: 02-25-2006, 03:39 AM
  2. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM
  3. Need help with calculator program
    By Kate in forum C# Programming
    Replies: 1
    Last Post: 01-16-2004, 09:48 AM
  4. Need help in RPN calculator
    By Lost__Soul in forum C Programming
    Replies: 14
    Last Post: 05-29-2003, 02:01 PM
  5. Replies: 2
    Last Post: 05-10-2002, 04:16 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21