+ 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?

18th Aug 2019, 11:27 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
7 Answers
+ 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 }
19th Aug 2019, 1:10 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
Hatsy Rei i just tried to use that code to test it and it doesnt work
31st Aug 2019, 1:19 AM
Danger
Danger - avatar
+ 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.
31st Aug 2019, 1:33 AM
Hatsy Rei
Hatsy Rei - avatar
+ 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.
31st Aug 2019, 1:37 AM
Danger
Danger - avatar
+ 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
31st Aug 2019, 1:45 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
Yep wrong lib. Thx Hatsy Rei
31st Aug 2019, 1:49 AM
Danger
Danger - avatar
+ 1
I dont know anything about C++ but is there a way to type cast maybe? Edit: http://www.cplusplus.com/doc/oldtutorial/typecasting/
19th Aug 2019, 12:36 AM
Ole113
Ole113 - avatar