C ++ python.h - 如何评估字符串? [英] C++ python.h - how to evaluate a string?

查看:127
本文介绍了C ++ python.h - 如何评估字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。

之前我从未使用过Python.h,但我确实知道Python。

我正在尝试制作一个计算器,我需要评估一个包含数学运算的字符串。

因此字符串2 + 2 * 2将变为 6

在常规Python中,我只使用

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

eval("2+2*2")



我不知道如何在C ++中使用Python.h做同样的事情。



值得一提的是,我的Python版本是3.7



我是什么尝试过:



我还没有尝试过任何东西,因为我甚至不知道从哪里开始。


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.

推荐答案

如果您尝试在纯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

这篇关于C ++ python.h - 如何评估字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆