Code for calculator

Posted on 2007-11-26
Last Modified: 2010-08-05
I need code for a c++ calculator that is based on a stack data structure. It must be able to evaluate expressions like :

( 3 * 4) + ( 6 + 2)
3 + 4
(6 *9) / (2 * 4)

Thank you
Question by:kk_hutton

Expert Comment

ID: 20348925
refer the link
it uses infix. if you are familer with tree traversal methods, then you can try with prefix and post fix aswell
LVL 39

Expert Comment

ID: 20350155
In the 'Annotated C++ Reference' of Bjarne Stroustrup there was a calculator sample. It was 15 years ago where I enhanced it to a class based sample and add some more functions and operand handling. But the basic sample was rather complete and it should not be difficult to google for it.

Regards, Alex
LVL 39

Expert Comment

ID: 20350185
BTW, is it a homework assignment? EE experts may not post full code samples for homework. So, if it is homework I only could help if you show some attempts of you to solve the problem yourself.
The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.


Author Comment

ID: 20352119
based on my other post you can probably see i attempted  and I couldnt get it to work. thats why im paying to get some help.
LVL 39

Accepted Solution

itsmeandnobodyelse earned 500 total points
ID: 20352818
>>>> thats why im paying to get some help.
Nevertheless there are the EE rules:

   - no full code to homework questions.
   - a maximum of 500 points for one question

As experts don't get anything from your money, you hardly can buy anyone over ;-)

I looked into the other thread. Where did you get the starter code from? The problem with code that wasn't designed by yourself is, that you hardly can get it corrected.

>>>> In addition,  this program must use a stack to implement the calculation
You could do it without explicit stack by using recursive calls. That way C++ makes the stack (call stack). Is the Stack class you used from a previous project? If you have to use that class you nevertheless should adopt it to your purposes. It shouldn't collect char strings but 'tokens'. A 'token' can be any operator or operand or delimiter. You best make a enum to 'classify' your tokens:


with the 'MAX_TOKEN' which must be last, you have an automatic 'count' of all tokens which can be used like

  char* szToken[MAX_TOKEN] = { "", "(", ")", "+", "-", "*", "/", .... };

I made it strings rather than single chars in case you will ahve operators with more than one character.

You then can make

struct Token
      CalcToken tokentype;
      double value;

Normally I would derive Operand, Operator, Delimiter from struct Token, but I don't want to confuse you. You could use the struct Token as data for the Stack. Whenever you parsed a token (by strtok) you decide

  - whether to add it to a new Stack
  - whether you can calculate teh current Stack,
     close it and put the result as Operand token
     to the previous Stack
  - whether to add it to the current Stack

E. g.  

    3 * 66 + (2 + 5)

1. should create a new Stack and add NUMBER token

  S[0]: { NUMBER 3 }

2. Add  STAR token
  S[0]: { NUMBER 3 }   { STAR }

3. Add NUMBER token

  S[0]: { NUMBER 3 }   { STAR }  { NUMBER 66}

4. When recognizing the '+'

4a)  evaluate Stack 0: "3 * 66" by popping the tokens from the stack and
       use a switch statement to do the appropriate action

    double result = 0;
    CalcToken oper = INITIAL;
    switch (token.tokentype)
        case NUMBER:
              switch (oper)
                  case INITIAL: result = token.value; break;
                  case STAR:    result *= token.value; break;
        case PLUS:    oper = PLUS;  break;
        case STAR:    oper = STAR;  break;

Finally the current Stack can be deleted and the result must be added to the previous stack. If there is no previous stack, create a new stack and put the result as initial token ...

In case of a parantheses you open a new stack and wait for the closing parantheses ... and so on. Finally the result of out last stack is the final result.

Regards, Alex


Author Comment

ID: 20353236
Actually I wrote the starter code from scratch and on my own. Believe it or not,  Im not trying to "buy" anyone over, Im trying to get help. I asked for help on the parenthesis part, and people suggested I wrote it using different methods I don't know how to write. Please don't make assumptions. Thanks for your help
LVL 40

Expert Comment

ID: 20376857
Alex is right!

If this is homework then we are not allowed to post full code examples. That's EE rules, we don't make them but also we don't break them. Look at the code you already have, identify what you don't understand and ask specific questions here. You'll find EE experts will be only too willing to assist with specific problems but not one of them will post you full code -- no  matter how many times you say you've tried but can't do it! If you are that stuck you'll need to refer back to your professor.


Featured Post

Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

821 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question