0

I want to use C++ to make a calculator, so that I can enter an expression and calculate the result.

For example,

input

(5.2+4)*ln3.4+sin3

output

11.39985

The problem is that I don't know how to separate the number and the operator from the string. For the length of the operands and numbers are different. Is there any good way?

liushi
  • 73
  • 5
  • 3
    Let me just say that the problem you're trying to solve is not as trivial as you seem to believe. You have to know how to do parsing and lexical analysis, something way too much for a simple answer. – PaulMcKenzie Oct 05 '19 at 23:25
  • 1
    You can clean a number of ideas and helpful hints just by entering `"[c++] calculator"` in the search box at the top of the window. – David C. Rankin Oct 05 '19 at 23:27

2 Answers2

0

Use a library such as exprtk.

I'm going to assume that you're a total noob which leads me to advise you to always Google for a library that solves your problem.

vaid
  • 1,292
  • 11
  • 29
0

That's actually a much harder problem than it seems at first, and I say that from experience.

If you want an example of how to do it completely from scratch, here is a question where I posted an example I was working on. It is certainly not complete, but links to a great Java article (actually, probably the best article) on Pratt parses, which in my opinion is the best way to parse expressions. My question was on my attempt to port the Java code found there to C++. You can see a problem I ran into there.

You will also need to know some theory on lexers, and learn how to create tokens, which I don't ask about there.

The point is, you have a lot of research ahead of you, if you want to start from scratch, or even if you want to just know the theory of what's going on, but I certainly encourage you to try it if you don't have a deadline for it.