[英]Is there anyway to convert String into executable c++ expression?
Say i have a string var x = 2 + 3 ;假设我有一个字符串 var x = 2 + 3 ; i can convert it into expression in javasript using eval();
我可以使用 eval() 将其转换为 javasript 中的表达式; is there any way to convert string into executable c++ expression same as eval ( using built-in function or customize code ) ?
有什么方法可以将字符串转换为与 eval 相同的可执行 C++ 表达式(使用内置函数或自定义代码)? what i mean to do is try to find out result of a one variable linear equation .
我的意思是尝试找出一个单变量线性方程的结果。 I found this code in c++ forum
我在 C++ 论坛中找到了这段代码
#include <iostream>
struct VAR{
float i;
};
struct LINE{//k*x+a
float a, k;
VAR* x;
LINE(){}
LINE(int a) : a(a), k(0), x(0) {}
LINE(VAR& v) : a(0), k(1), x(&v) {}
};
LINE operator + (LINE A, LINE B){//assumes that A.x == 0 or B.x == 0 or A.x == B.x
LINE R;
R.a = A.a + B.a;
R.k = A.k + B.k;
if(A.x) R.x = A.x;
else R.x = B.x;
return R;
}
LINE operator - (LINE A, LINE B){//same as +
LINE R;
R.a = A.a - B.a;
R.k = A.k - B.k;
if(A.x) R.x = A.x;
else R.x = B.x;
return R;
}
LINE operator * (LINE A, LINE B){//assumes that A.x == 0 or B.x == 0
LINE R;
R.a = A.a * B.a;
R.k = A.k * B.a + B.k * A.a;
if(A.x) R.x = A.x;
else R.x = B.x;
return R;
}
LINE operator / (LINE A, LINE B){//assumes that B.x == 0
LINE R;
R.a = A.a / B.a;
R.k = A.k / B.a;
R.x = A.x;
return R;
}
void operator == (LINE A, LINE B){
LINE C = A - B;
C.x->i = -C.a/C.k;
}
int main(){
VAR x;
5 == (2 + (x-7)*10)/2;
std::cout << "x = " << x.i;
std::cin.get();
return 0;
}
its work fine.它的工作正常。 Now what i want to do is execute this "5 == (2 + (x-7)*10)/2;"
现在我想要做的是执行这个“5 == (2 + (x-7)*10)/2;” statement as eval in c++ .
声明为 c++ 中的 eval 。
Edit 1: Thank you all , problem is solved :)编辑1:谢谢大家,问题解决了:)
Alas, as Joachim pointed out, C++ is a statically compiled language, not an interpreted or dynamically compiled language like Java, Python, ... are.唉,正如 Joachim 所指出的,C++ 是一种静态编译语言,而不是像 Java、Python 那样的解释性或动态编译语言。 So, there is no such a function
eval()
in standard C++.因此,标准 C++ 中没有这样的函数
eval()
。
However, you may be interested in Embedded Ch , an embeddable C++ interpreter that provides such eval()
function and more.但是,您可能对Embedded Ch感兴趣,这是一个可嵌入的 C++ 解释器,它提供了这样的
eval()
函数等等。 It is not free software, though.不过,它不是免费软件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.