473,569 Members | 2,459 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Calculating mathematical expressions in C with getchar()

2 New Member
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:

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.  
  3. int main(){
  4.     int ch;
  5.     int num = 0,temp=0;
  6.     char op;
  7.     while ((ch = getchar())!= EOF){
  8.         if (ch != '\n'){
  9.         if (ch >= '0' && ch <='9'){ 
  10.             num = num*10 + ch- '0'; 
  11.             }else {
  12.                 op = ch;
  13.             temp = num;
  14.             num = 0;
  15.            }
  16.         }
  17.     int result =0;
  18.     switch(op){
  19.         case '+':
  20.             result = temp + num;
  21.                break;
  22.         case '-':
  23.                result = temp - num;
  24.             break;
  25.         case '*':
  26.             result = temp * num;
  27.                break;
  28.         case '/':
  29.               result = temp / num;
  30.                break;
  31.     }
  32.     if (ch == '\n'){
  33.         printf("%d\n",result); 
  34.         num = 0;
  35.         temp = 0;
  36.         }
  37.  
  38.     }
  39. }
  40.  
Dec 2 '18 #1
1 1374
weaknessforcats
9,208 Recognized Expert Moderator Expert
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.
Dec 3 '18 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

8
2099
by: Tonino | last post by:
Hi, I have a task of evaluating a complex series (sorta) of mathematical expressions and getting an answer ... I have looked at the numarray (not really suited??) and pythonica (too simple??) and even tried using eval() ... but wondered if there were other packages/modules that would enable me to to this a bit easier... The...
1
287
by: Picho | last post by:
Hi all, first of all, does anyone know of a newsgroup dedicated for regular expressions? second - my problem: I have a string that represents a formula of the format: "formula(...)" the formula itself can contain other formula expressions like "Calc(...)", "Assign(...)" etc
3
2236
by: Cam | last post by:
Hi everyone, Before I answer to a (hopefully) helpful reply to this post, I have been rapped over the knuckles for 'top-posting' and I do not wish to be a learner poster who observes poor netiquette as I am a firm believer in consideration .... to this end, could somebody please tell me how I reply to a message without top-posting? Do I...
5
7889
by: mojo | last post by:
Is there a nice way to have HTML display mathematical expressions that contain radical symbols (square root, cube root, ..., nth root) that look nice. The best I can come up with is by having a table, a CSS border, the radical sign: <TABLE> <TR> <TD>&radic</TD><TD style="border-top: 1pt solid black;">103</TD> </TR>
3
5190
by: tobimarq | last post by:
hi all, I wonder if the following is possible in php: I want php to 'interpret' a string that contains (a simple kind of) mathematical calculation, like $var='25*3'; $result= (int) $var; //according to the php manual, $result contains 25, //but I want the result at the end to contain: 75 Is there a php function or construct, that does...
2
1439
by: Tim Conner | last post by:
How can I use regex to split an expression like the following : (Round(340/34.12)*2) into this list : ( Round ( 340
2
12279
kadghar
by: kadghar | last post by:
Many people asks if there is a way to write a mathematical expression, writen as a string in a text box, so they can do something like: sub something_click() textbox2.text=eval(textbox1.text) end sub Well, of course it's posible, and can be done with some characters mannaging. This way you can complicate it as much as you want. The way...
2
2485
by: jtanz0 | last post by:
Im fairly new to java programming although i have some experience in python. I have to create a calculator program (command line) which takes as input a mathematical expression consisting of decimal numbers and the four basic mathematical operators (+,-,/,*) and correctly handles nested mathematical expressions. Some examples: • 5 + 6 * 2...
22
3537
by: arnuld | last post by:
Mostly when I want to take input from stdin I use getchar() but I get this from man page itself: "If the integer value returned by getchar() is stored into a variable of type char and then compared against the integer constant EOF, the comparison may never succeed, because sign-extension of a variable of type char on widening to integer is...
0
1317
by: fahima | last post by:
This is an idea to develop a mathematical tool/application which accepts mathematical symbols, expressions, equations from the end user in the form of text, audio and video. This feature enhances capability of the application. This application also has the feature to develop mathematical solution/model of a problem by helping the user via text,...
0
7703
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7926
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8132
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7678
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6286
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5514
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3644
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2116
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1226
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.