且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++ python.h - 如何评估字符串?

更新时间:2023-02-03 09:03:43

如果您尝试在纯C / C ++中执行此操作,我不知道任何类似的功能,但谷歌可能会找到一些第三方库。如果您尝试使用C / C ++中的python库,请查看 Python / C API参考手册 - Python 3.4.9文档 [ ^ ]。
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[^].


在C / C ++中没有类似的东西,因为它是一种编译语言。那些没有像 eval()这样的函数,因为这需要编译器(将字符串翻译成机器代码)作为创建的应用程序的一部分。



Python基本上是一种解释型语言(即使使用Python实现预编译到中间代码)。这些需要目标机器上的可执行文件,最终通过翻译源代码或中间代码来执行程序。



如果你需要C / C ++中的这样的功能,你需要一个解释器作为应用程序的一部分或被称为外部程序。
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.


在C ++中你有两个选项,第一个也是最简单的是你评估不是那个字符串,但从UI获取所需的操作并进行计算。 (从按钮输入中获取数字和运算符)或者您必须自己解析数字和运算符的字符串数据,而不是解决它。我在Github上找到了 DescCalc项目。但要注意:它可能太复杂,无法满足您的需求。



我会编写一个解析器来评估数字和运算符的输入字符串。尊重数学规则,如:



a * b + c

(a + b)* c
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

>