Public Group

# C++ mini calculator project

This topic is 4407 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I am trying to design a simple console calculator that uses functions such as; Add or Square. The aim is for the user to type in a function like what I listed above and then are prompted to type numbers for example; Add 5 6 answer would then return as 11. I tried using a switch statement but then realised it would never work that way and then thought about using if and else statements but that would take forever. Is there an easier way to do this?

##### Share on other sites
Sounds like you want to make a reverse-polish-notation calculator. Your best bet is to read up a bit on that type of calculator, and keep in mind this type of thing is most easily done with a queue.

This is actually a pretty common C++ course assignment ;) I did it a few semesters ago. Good luck! Hopefully this gets you on the right track.

I'd write more, but that takes the fun out of the experience. If you need more hints, just ask ;)

##### Share on other sites
Sounds like a good application for recursion here. If we assume you have a get_token funtion that returns the type of the next token from your input and makes its text rep available through token_text(), and a to_int(std::string) function that converts a string to an int,

int norm(){    token_type t=get_token();        switch(t)        {        case ttAdd   : return norm()+norm();        case ttSub   : return norm()-norm();        case ttNumber: return to_int(token_text());        default: throw SomeKindOfError();        }    }

I think that will work, although I can't test at the moment. That would have the implication that you could do:

to be interpreted as 2+(1+(4-3))

##### Share on other sites
in general if you are tokenizing and then evaluating using a binary expression tree, you can treat a function as a high-precedence operator. for example:

damn CODE tags don't preserve my ascii art lol. well point is say pow is an operator that is a node in the tree. the left child node would be the first parameter, the right child node would be the second parameter. when you are building the tree though you have to specialize your grammar to accommadate

<function_name> <numeric value>
and
<function_name> <(> <expression> <)> (handled as urnary operator)
and
<function_name> <(> <expression1> <,> <expression2> <)> (handled as binary operator)

[Edited by - yadango on November 16, 2006 4:18:52 AM]

1. 1
2. 2
3. 3
Rutin
21
4. 4
5. 5
khawk
14

• 9
• 11
• 11
• 23
• 12
• ### Forum Statistics

• Total Topics
633654
• Total Posts
3013171
×