+ 3
C++ - Any way to emulate an "eval"?
You have a string in C++ representing an expression, e.g. "3%2+4*3". Any way in C++ to evaluate the expression, in the example to 13?
7 Respostas
+ 4
There is no eval equivalent in C/C++. You will have to write rules to parse the string yourself, or you can create a program which compiles and invokes specific code segments - An easier hack but most likely platform dependent.
int main() {
std::string expr = "1+1";
std::ofstream obj;
// output expr to .cpp file
// call gcc/c++ to compile .cpp
// run the output file
}
+ 3
Hatsy Rei i just tried to use that code to test it and it doesnt work
+ 3
Dangerzone47
"It doesn't work" is a really vague statement especially when the "code" I gave is merely a very general concept of how it should work. If you need help, post your code.
+ 3
Sorry Hatsy Rei i forgot to say the error. It says: error: aggregate 'std::ofstream obj' had incomplete type and cannot be defined. the code is really a copy/paste of yours with an output statement with it, to test.
+ 3
Dangerzone47 You still did not show your code, but I'll just assume you didn't include the header for file streams.
http://www.cplusplus.com/reference/fstream/fstream/
https://stackoverflow.com/questions/1057287/ofstream-error-in-c
+ 2
Yep wrong lib. Thx Hatsy Rei
+ 1
I dont know anything about C++ but is there a way to type cast maybe?
Edit: http://www.cplusplus.com/doc/oldtutorial/typecasting/