Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi.
I've never used Python.h before, but I do know Python.
I'm trying to make a calculator and I need to evaluate a string containing math operations.
So a string "2 + 2 * 2" would become 6.
In regular Python I'd just use
Python
eval("2+2*2")

I don't know how to do the same in C++ with Python.h though.

It's also worth mentioning, that my version of Python is 3.7

What I have tried:

I haven't really tried anything, because I don't even know where to start.
Posted
Updated 5-Aug-18 7:51am
v2

If you are trying to do this in pure C/C++ I am not aware of any similar function, but there may be some third party library that google can find for you. If you are trying to use a python library from C/C++ then take a look at Python/C API Reference Manual — Python 3.4.9 documentation[^].
 
Share this answer
 
Comments
Member 13020023 5-Aug-18 11:15am    
I'm not trying to do this in pure C++. I'm asking on how to do this with Python.h.
Richard MacCutchan 5-Aug-18 11:17am    
What does that actually mean? Python.h sounds like a C/C++ header file.
Richard MacCutchan 5-Aug-18 11:19am    
I just checked; you need to follow the link I gave you in my answer.
There is nothing like that in C/C++ because it is a compiled language. Those don't have functions like eval() because that would require the compiler (which translates strings into machine code) being part of the created application.

Python is basically an interpreted language (even when using a Python implementation precompiling to intermediate code). These require an executable on the target machine that finally executes the program by translating the source code or the intermediate code.

If you need such functionality in C/C++, you need an interpreter as part of the application or be called as external program.
 
Share this answer
 
Comments
Member 13020023 5-Aug-18 11:26am    
What about Python.h? Do you know any examples?
Jochen Arndt 5-Aug-18 17:50pm    
You can embed Python in C/C++ (call Python code using an installed Python interpreter) as explained at
https://docs.python.org/3.1/extending/embedding.html

In C++ you have two options, first and easiest is that you evaluate not that string, but fetch the needed operations from the UI and calculate it. (Get the numbers and operators from the button input) or you must parse the string data for numbers and operators yourself and than work it out. I found theDescCalc project on Github. But be aware: it may be too complex for your needs.

I would write a parser which is evaluate the input string to numbers and operators. Respect the rules of math like for:

a * b + c
(a + b) * c
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900