473,657 Members | 2,394 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Read string for arithmetic operation

Hello everyone,

I have a question regarding how to interpret a string.

Basically I want to write a little calculator, I will type something
like "12+69*12-44/2" and then want my program to compute it into the
result :)

I experimented a bit with strtok and the like, but I think I am not sure
how I should approach this problem. The problem being the priorities of
the operators of course.

Should I split the string? Right now I just put all numbers in a list,
so I would get:
12->69->12->44->2
Now I could make the same for the signs like +->*->-->/ and try to sort
things out and so on, I am really not sure.

Anyone got a hint for me how to do this?
I am thankful for any idea.

Thomas
Aug 3 '06 #1
4 4693
Thomas Kreuzer wrote:
Hello everyone,
I have a question regarding how to interpret a string.

Basically I want to write a little calculator, I will type something
like "12+69*12-44/2" and then want my program to compute it into the
result :)

I experimented a bit with strtok and the like, but I think I am not sure
how I should approach this problem.
strtok is a problematic function. I would recommend you do it via the
strcspn(p) functions.
[...] The problem being the priorities of
the operators of course.

Should I split the string? Right now I just put all numbers in a list,
so I would get:
12->69->12->44->2
Now I could make the same for the signs like +->*->-->/ and try to sort
things out and so on, I am really not sure.

Anyone got a hint for me how to do this?
The key is to to scan the expression, and first of all distinguish
between subtraction and negation. Then what you do is you find the
first operator with the *least* precidence. So in your case, its the
"+" after the "12". Then you recursively calculate each parameter for
the operation, in this case "12" and "69*12-44/2", which will end up as
12 and the other as 806. Then switch on the operator "+" to an
addition code snippet, which would add the two results to get 806 + 12
= 818. Then just return this final result.

The tricky part is basically keeping track of parenthesis levels and
detecting the difference between negation and subtraction. Negation
has higher precidence than subtraction, so this actually makes a big
deal. So you'll know things are sort of working when you can parse:

1-2----(--3-4)-5

correctly.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Aug 3 '06 #2
Thomas Kreuzer wrote:
Hello everyone,

I have a question regarding how to interpret a string.

Basically I want to write a little calculator, I will type something
like "12+69*12-44/2" and then want my program to compute it into the
result :)

I experimented a bit with strtok and the like, but I think I am not sure
how I should approach this problem. The problem being the priorities of
the operators of course.

Should I split the string? Right now I just put all numbers in a list,
so I would get:
12->69->12->44->2
Now I could make the same for the signs like +->*->-->/ and try to sort
things out and so on, I am really not sure.

Anyone got a hint for me how to do this?
assuming that operands is the list of operands and
operators is the list of operators:

12+69*12-44/2
=[12 69 12 44 2] (array of operands)
=[+ * - /] (array of operators)
while (operators has at least one operator) {
i = first position of * or / in operators
if no * or / found, then i = first operator
apply operators[i] on operands[i] and operands[i+1]
store result in operands[i]
remove operands[i+1]
remove operators[i]
}

Try changing the steps to include correct parsing
of nested braces.

goose,

Aug 4 '06 #3
The question is what is faster, or "better".
Is the list approach useful? Or should I try to make it recursively like
it was suggested? Most of the time recursions are slower then
iterations, but with lists I have to go through them a lot of times etc.

My main goal will not be just a simple calculator but I want actually
matrix operations implemented and this is then my underlying function to
compute all arithmetic expressions. So it should be as fast as possible
with my abilities :)

A compile must have a similar algorithm, how do they parse the strings?

Thanks in advance,
Thomas
Aug 4 '06 #4
Thomas Kreuzer wrote:
>
The question is what is faster, or "better". Is the list approach
useful? Or should I try to make it recursively like it was
suggested? Most of the time recursions are slower then iterations,
but with lists I have to go through them a lot of times etc.

My main goal will not be just a simple calculator but I want
actually matrix operations implemented and this is then my
underlying function to compute all arithmetic expressions. So it
should be as fast as possible with my abilities :)

A compile must have a similar algorithm, how do they parse the
strings?
You neglected to quote whatever you are replying to, and the result
makes no sense. Always ensure your articles stand by themselves.

I suspect you are trying to convert a text string into an
arithmetic expression. This requires a lexical analyser, probably
best followed by conversion to reverse Polish notation (look that
up), together with suitable error detection.

--
Chuck F (cb********@yah oo.com) (cb********@mai neline.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.netUSE maineline address!
Aug 5 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

43
26496
by: Mehta Shailendrakumar | last post by:
Hello, Can anyone suggest me operator to perform arithmetic shift in C? May it be for a perticular compiler. Thank you in advance. Regards, Shailendra
17
4653
by: Chad Myers | last post by:
I've been perf testing an application of mine and I've noticed that there are a lot (and I mean A LOT -- megabytes and megabytes of 'em) System.String instances being created. I've done some analysis and I'm led to believe (but can't yet quantitatively establish as fact) that the two basic culprits are a lot of calls to: 1.) if( someString.ToLower() == "somestring" ) and
4
4138
by: Tom | last post by:
I have a VB.NET framework 1.1 application that I am installing on my user's workstation. It works fine on EVERY machine except for one - on this one machine it generates a 'Overflow or underflow in the arithmetic operation' when I attempt to instantiate my first form, as so: Dim frm As New frmMyForm() Based on some things I saw here, I thought it might be that this workstation didn't have a MS Sans Seriff font on it (since that is the...
46
2121
by: Albert | last post by:
Why doesn't: #include <stdio.h> void reverse(char, int); main() { char s;
44
6697
by: gokkog | last post by:
Hi there, There's a classic hash function to hash strings, where MULT is defined as "31": //from programming pearls unsigned int hash(char *ptr) { unsigned int h = 0; unsigned char *p = ptr;
11
1899
by: sethukr | last post by:
hi everybody, char str="string"; str^=str; can anybody plz tell me the use of ^operator in string??? -Sethu
9
1842
by: Mike Aubury | last post by:
Is there any standard (or even non-standard) way to detect limit overflow in arithmetic in C ? eg. /* assuming 4 byte ints.. */ int a=2147483647; int b=2147483647; int c;
7
1564
by: Mike TI | last post by:
Nov 13, 2007 Hi all Can I build a string for arithmetic operation. (VB NET 2005) e.g. I want to build an arithmetic operation from within the program as
10
5938
by: vincex200 | last post by:
My group needs help with this program. We attempted to start it and got no where. Please help us. Write a C++ program that will read data from a file, perform computation on the data, then print the result to another file. The data from the file will contian 100 lines where each line contains three items. The three items are an arithmetic operation followed by two integer values (non zero.) The program should perform the arithmetic operation...
0
8324
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8842
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8516
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
7353
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6176
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2743
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
2
1970
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1733
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.