0

How to execute code from string in c++

-

12th Oct 2020, 3:51 PM
return 0;
return 0; - avatar
6 Réponses
+ 2
Can you provide more details about it and also some examples.
12th Oct 2020, 3:53 PM
Arsenic
Arsenic - avatar
+ 2
hussein Unfortunately C++ does not have an eval function like JS and as such it is not directly possible for one to execute strings as valid code. But here is my workaround,(though I've not yet tried it) 1.Write some code and store it in a string.(Use raw strings preferably) 2.Write the string to a temporary file 3.Use system() to invoke the compiler and compile your code 4.Still use system() to execute the program and afterwards, to delete all the temporary files created.
12th Oct 2020, 7:39 PM
Anthony Maina
Anthony Maina - avatar
+ 1
Compile and run
12th Oct 2020, 4:08 PM
Shadoff
Shadoff - avatar
0
I want to execute a string like string s = "cout << 4"; but in string i want to execute s how to?
12th Oct 2020, 7:31 PM
return 0;
return 0; - avatar
0
It worked lol
12th Oct 2020, 8:15 PM
return 0;
return 0; - avatar
0
C++ is compiled to binary so you can't write source code while executing, but there are two alternative ways: 1.write your string to a file and compile it then open the target. But it dome times you don't have compiler in that device and also compiling may take too long. 2.if your available instructions of code are limited you can use some IF or SWITCH code in order to make a function do some thing according to a string.
24th Mar 2023, 8:31 AM
L.M