This question already has an answer here:
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.
Straight-forward way:
string
tostd::function<void()>
cin
input stringstring
by spaces to astring
arrayArguments are hard to implement this way.
Better way:
Use LUA, Squirrel, Angel Code, JS, Python, or any other C/C++ embedded language available.
Maybe the simplest thing would be to use a
std::map
ofstd::function
objects:Live example.
Depending on your requirements you may need something more sophisticated than this however and at some point of complexity you might want to consider embedding a scripting language like Lua.