This question already has an answer here:
- Calling a Function From a String With the Function’s Name in C++ 8 answers
I'm working on a project and I need a way of receiving input from the console/user and use that to run a certain part in the code without the need of elaborate switch/if:else statements. Let me give you an example.
#include <iostream>
#include <string>
using namespace std;
void foo();
void foo2();
int main(){
string s;
cin >> s;
/*Take the input from cin and turn it into a function call, or some other
form of runnable code, like so*/
//Lets say the user inputs "run foo"
foo();
//Or if they input "run foo2"
foo2();
return 0;
}
void foo(){
cout << "Foo works, yay :D";
}
void foo2(){
cout << "Foo2 works, yay :D";
}
You might think I could do this with a switch or multiple if:else statements but this little code is just a small representation of what I need to do. The project requires this to be used on a large scale and I'd like it if I didn't need to use those, to save lines.
So is there any way I can do this in C++? Where the console user tells the program what to run and it runs said function?
Thanks!!
EDIT This is not a duplicate of the string to function call as this gets the input directly from the user versus from the program. As well as the answers show that you can use lua to do this since it is from user input.