Calculating mathematical expressions in C with getchar()

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jason4567
    New Member
    • Dec 2018
    • 2

    Calculating mathematical expressions in C with getchar()

    I want to create a program in C language that calculates mathematical expressions like 23+45*8 and returns the result of it.
    I have already tried to solve this problem but the program I made is working only for two numbers and I can do only one operation each time.
    How can I make this program work for many numbers and many operations?
    Any ideas or suggestions would be helpful.
    Here is also the code:

    Code:
    #include <stdio.h>
    
    int main(){
        int ch;
        int num = 0,temp=0;
        char op;
        while ((ch = getchar())!= EOF){
            if (ch != '\n'){
    	    if (ch >= '0' && ch <='9'){ 
    	        num = num*10 + ch- '0'; 
                }else {
                    op = ch;
    	        temp = num;
    	        num = 0;
               }
            }
    	int result =0;
    	switch(op){
    	    case '+':
    	    	result = temp + num;
    	       	break;
    	    case '-':
    	       	result = temp - num;
    	        break;
    	    case '*':
    	        result = temp * num;
    	       	break;
    	    case '/':
    	      	result = temp / num;
    	       	break;
    	}
    	if (ch == '\n'){
    	    printf("%d\n",result); 
    	    num = 0;
    	    temp = 0;
            }
    	    
        }
    }
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    This is usually done with two stacks. One for the values and one for the operation.


    Let's assume two stacks: Value and Operation.

    So 3 + 4 + 5 is parsed to

    3 push to Value
    + push to operation

    4 push to value

    + push to operation


    5 push to value.

    So the stacks look like

    Value
    5
    4
    3

    Operation

    +
    +

    To solve, pop the operation. It's a +.

    Next, pop value twice for the numbers 5 and 4.

    + is an addition so add 5 and 4 and push the result back onto Value.

    Value now looks like:

    9
    3

    Pop the operation for the second plus.


    It's another add so pop Value twice for the numbers 9 and 3.

    Add 9 and 3 and push the 12 back onto the Value stack.

    Now pop the operation again and we see that it's empty. That means the final result is on top of the Value stack.


    Pop the 12 as your answer.

    This is just a teaser. A little research here will give you ideas on handle parenthetical expressions and all sorts of things.

    Comment

    Working...